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. 值得一做》关于一道暴搜BZOJ1024(EASY+)

    为什么要写这道题的DP捏? 原因很简单,因为为原来在openjudge上有一道题叫分蛋糕,有一个思路和这道题很像:“分锅”. 分锅:即为考虑计算当前情况的最优解时,把当前状态结果,分散为考虑当前状态的 ...

  2. 71. Simplify Path压缩文件的绝对路径

    [抄题]: Given an absolute path for a file (Unix-style), simplify it. For example,path = "/home/&q ...

  3. Python PyInstaller 打包报错:AttributeError: 'str' object has no attribute 'items'

    pyinstaller打包时报错:AttributeError: 'str' object has no attribute 'items' 网上查询,可能是setuptools比较老: 更新一下 p ...

  4. [Fiddler] 在 Composer 中对HTTP报文进行编辑,重新执行

    如果想要对某个HTTP请求进行编辑,然后重新执行观察结果,可以将这个报文从左侧拖放到右侧的Composer里面 这样就可以很方便的修改HTTP请求的方法,报文头,报文体 在用 SoapUI 做 API ...

  5. 基于redis实现分布式Session

    学习到好的知识还是需要记录下来的. 开发环境 asp.net mvc4,iis.asp.net 自带的session机制存在诸多不好的地方.先只要列出几点. asp.net mvc 默认的sessio ...

  6. 认识Web前端、Web后端、桌面app和移动app新开发模式 - 基于Node.js环境和VS Code工具

    认识Web.桌面和移动app新开发模式 - 基于Node.js环境和VS Code工具 一.开发环境的搭建(基于win10) 1.安装node.js和npm 到node.js官网下载安装包(包含npm ...

  7. OBD Problem Vehicles

    This page contains a list of vehicles that are known to be non-compliant with OBD-II in one way or a ...

  8. Union、Union All、Intersect、Minus

    转自:http://www.2cto.com/database/201208/148795.html Union:对两个结果集进行并集操作,不包括重复行,同时进行默认规则的排序: Union All: ...

  9. 10.13DOM中document--文档1找到元素的方法,还有元素内容属性

    今天讲了js的组成部分中的第二组成部分(DOM),DOM包括以下内容: window    -- 窗口                                                 ...

  10. 安卓利用Handlers,AsyncTask和Loaders运行后台程序

    安卓的用户界面线程(user interface thread) 1.1 主线程 安卓修改用户界面并从一个单一用户界面线程中处理输入事件,这个线程也被称作主线程(main thread) Androi ...