This article shows how to access MongoDB data using an Entity Framework code-first approach. Entity Framework 6 is available in .NET 4.5 and above.

Entity Framework is an object-relational mapping framework that can be used to work with data as objects. While you can run the ADO.NET Entity Data Model wizard in Visual Studio to handle generating the Entity Model, this approach, the model-first approach, can put you at a disadvantage if there are changes in your data source or if you want more control over how the entities operate. In this article you will complete the code-first approach to accessing MongoDB data using the CData ADO.NET Provider.

    1. Open Visual Studio and create a new Windows Form Application. This article uses a C# project with .NET 4.5.
    2. Run the command 'Install-Package EntityFramework' in the Package Manger Console in Visual Studio to install the latest release of Entity Framework.
    3. Modify the App.config file in the project to add a reference to the MongoDB Entity Framework 6 assembly and the connection string.

      Set the Server, Database, User, and Password connection properties to connect to MongoDB. To access MongoDB collections as tables you can use automatic schema discovery or write your own schema definitions. Schemas are defined in .rsd files, which have a simple format. You can also execute free-form queries that are not tied to the schema.

      <configuration>
      ...
      <connectionStrings>
      <add name="MongoDBContext"connectionString="Offline=False;Server=MyServer;Port=27017;Database=test;User=test;Password=Password;"providerName="System.Data.CData.MongoDB" />
      </connectionStrings>
      <entityFramework>
      <providers>
      ...
      <provider invariantName="System.Data.CData.MongoDB" type="System.Data.CData.MongoDB.MongoDBProviderServices, System.Data.CData.MongoDB.Entities.EF6" />
      </providers>
      <entityFramework>
      </configuration>
      </code>
    4. Add a reference to System.Data.CData.MongoDB.Entities.EF6.dll, located in the lib -> 4.0 subfolder in the installation directory.
    5. Build the project at this point to ensure everything is working correctly. Once that's done, you can start coding using Entity Framework.
    6. Add a new .cs file to the project and add a class to it. This will be your database context, and it will extend the DbContext class. In the example, this class is named MongoDBContext. The following code example overrides the OnModelCreating method to make the following changes:
      • Remove PluralizingTableNameConvention from the ModelBuilder Conventions.
      • Remove requests to the MigrationHistory table.
      using System.Data.Entity;
      using System.Data.Entity.Infrastructure;
      using System.Data.Entity.ModelConfiguration.Conventions;
       
      class MongoDBContext : DbContext {
      public MongoDBContext() { }
       
      protected override void OnModelCreating(DbModelBuilder modelBuilder)
      {
      // To remove the requests to the Migration History table
      Database.SetInitializer<MongoDBContext>(null); 
      // To remove the plural names   
      modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
      }
    7. Create another .cs file and name it after the MongoDB entity you are retrieving, for example, restaurants. In this file, define both the Entity and the Entity Configuration, which will resemble the example below:
      using System.Data.Entity.ModelConfiguration;
      using System.ComponentModel.DataAnnotations.Schema;
       
      [System.ComponentModel.DataAnnotations.Schema.Table("restaurants")]
      public class restaurants {
      [System.ComponentModel.DataAnnotations.Key]
      public System.String _id { getset; }
      public System.String borough { getset; }
      }
       
    8. Now that you have created an entity, add the entity to your context class:
      public DbSet<restaurants> restaurants { setget; }
    9. With the context and entity finished, you are now ready to query the data in a separate class. For example:
      MongoDBContext context = new MongoDBContext();
      context.Configuration.UseDatabaseNullSemantics = true;
      var query = from line in context.restaurants select line;

Access MongoDB Data with Entity Framework 6的更多相关文章

  1. AppBox升级进行时 - 拥抱Entity Framework的Code First开发模式

    AppBox 是基于 FineUI 的通用权限管理框架,包括用户管理.职称管理.部门管理.角色管理.角色权限管理等模块. 从Subsonic到Entity Framework Subsonic最早发布 ...

  2. Programming Entity Framework 翻译(2)-目录2-章节

    How This Book Is Organized 本书组织结构 Programming Entity Framework, Second Edition, focuses on two ways ...

  3. Productivity Improvements for the Entity Framework(实体框架设计)【转】

    Background We’ve been hearing a lot of good feedback on the recently released update to the Entity F ...

  4. Web Api 2, Oracle and Entity Framework

    Web Api 2, Oracle and Entity Framework I spent about two days trying to figure out how to expose the ...

  5. Professional C# 6 and .NET Core 1.0 - 38 Entity Framework Core

    本文内容为转载,重新排版以供学习研究.如有侵权,请联系作者删除. 转载请注明本文出处:Professional C# 6 and .NET Core 1.0 - 38 Entity Framework ...

  6. Professional C# 6 and .NET Core 1.0 - Chapter 38 Entity Framework Core

    本文内容为转载,重新排版以供学习研究.如有侵权,请联系作者删除. 转载请注明本文出处:Professional C# 6 and .NET Core 1.0 - Chapter 38 Entity F ...

  7. Entity Framework 6连接Postgresql、SQLite、LocalDB的注意事项和配置文件

    Postgresql Postgresql支持Code First的方式自动生成表,不过默认的模式是dbo而不是public,而且还可以自动生成自增主键. <?xml version=" ...

  8. 让EF飞一会儿:如何用Entity Framework 6 连接Sqlite数据库

    获取Sqlite 1.可以用NuGet程序包来获取,它也会自动下载EF6 2.在Sqlite官网上下载对应的版本:http://system.data.sqlite.org/index.html/do ...

  9. Entity Framework使用Sqlite时的一些配置

    前段时间试着用Entity Framework for Sqlite环境,发现了一些坑坑洼洼,记录一下. 同时试了一下配置多种数据库,包括Sqlite.Sql Server.Sql Server Lo ...

随机推荐

  1. 必看的 jQuery性能优化的38个建议

    一.注意定义jQuery变量的时候添加var关键字 这个不仅仅是jQuery,所有javascript开发过程中,都需要注意,请一定不要定义成如下: $loading = $('#loading'); ...

  2. 前端 webpack

    前端 webpack http://www.cnblogs.com/lvdabao/

  3. js中直接对字符串转义-用于solr ulr 关键词转义

    js代码 /* * 获取UTC格式的字符串,参数必须是 */var solrDateFormat = function (o){    var date;    if(typeof o == 'str ...

  4. Hibernate入门级实例

    一.开发环境 Win8 + jdk1.7 + MyEclipse + Tomcat5.0 + MySQL 说明:其实Hibernate是非常独立的框架,根本不需要MyEclipse,Eclipse,T ...

  5. Java 代理机制

    Table of Contents 1 引言 2 常见的代理 3 代理模式UML图 4 代理模式实例 5 java动态代理 5.1 java动态代理UML图 6 代理模式与装饰者模式的区别 6.1 装 ...

  6. html5标签---不常用新标签的整理

    状态标签 meter 用来显示已知范围的标量值或者分数值. value:当前的数值. min:值域的最小边界值.如果设置了,它必须比最大值要小.如果没设置,默认为0 max:值域的上限边界值.如果设置 ...

  7. 通过input上传图片,判断不同浏览器及图片类型和大小的js代码

    1.jsp页面代码 <form id="userPhoto" name="userPhoto" method="post" actio ...

  8. windows cmd命令相关知识和经验的碎片化记录

    1.循环遍历当前文件夹下的所有*.dll文件,并打印其绝对路径和相对路径 ``` for /f "tokens=*" %%a in ('dir /s/b/a-d "*.d ...

  9. sql语句表连接

    "Persons" 表: Id_P LastName FirstName Address City 1 Adams John Oxford Street London 2 Bush ...

  10. Http面试题

    http请求由三部分组成,分别是:请求行.消息报头.请求正文 HTTP(超文本传输协议)是一个基于请求与响应模式的.无状态的.应用层的协议,常基于TCP的连接方式,HTTP1.1版本中给出一种持续连接 ...