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. java 蓝桥杯基础练习 01字串 进制转换

    问题描述 对于长度为5位的一个01串,每一位都可能是0或1,一共有32种可能.它们的前几个是: 请按从小到大的顺序输出这32种01串. 输入格式 本试题没有输入. 输出格式 输出32行,按从小到大的顺 ...

  2. java算法 第七届 蓝桥杯B组(题+答案) 6.方格填数

    6.方格填数  (结果填空) 如下的10个格子 (如果显示有问题,也可以参看[图1.jpg]) 填入0~9的数字.要求:连续的两个数字不能相邻.(左右.上下.对角都算相邻) 一共有多少种可能的填数方案 ...

  3. 高性能Web服务器Nginx的配置与部署研究(10)核心模块之HTTP模块Location相关指令

    一.基本语法 语法:location [= | ~ | ~* | ^~] </uri/> {...} 缺省:N/A 作用域:server 二.匹配规则 1. 四种匹配方式 = 精确匹配 ~ ...

  4. 原生JS的使用,包括jquery和原生JS获取节点、jquery和原生JS修改属性的比较

    一.前言 相比于JS这条直达终点.满是荆棘的小路,jquery无疑是康庄大道了,足够的简洁.易用给了它辉煌的地位.然而,毕竟是绕着道的插件,当小路走着走着变成大路的时候,曾经的大路也就失去了他自身的优 ...

  5. 微信小程序文档里看不到的小Tips

    前几天折腾了下.然后列出一些实验结果,供大家参考. 0. 使用开发工具模拟的和真机差异还是比较大的.也建议大家还是真机调试比较靠谱. 1. WXML(HTML) 1.1 小程序的WXML没有HTML的 ...

  6. 二、SQL的生命周期

    MySQL的sql语句由客户端发出,经过连接和权限验证后,最终达到服务器端,由服务器分配thread线程处理,之后就是要介绍的具体服务器端的thread线程是怎么处理每条sql语句的.[ 了解thre ...

  7. Openssl rsa命令

    一.简介 Rsa命令用于处理RSA密钥.格式转换和打印信息 二.语法 openssl rsa [-inform PEM|NET|DER] [-outform PEM|NET|DER] [-in fil ...

  8. p4688 [Ynoi2016]掉进兔子洞

    传送门 分析 我们考虑先将所有数离散化 之后我们对于每个状态用一个bitset来记录 其中第i段表示颜色i的信息 对于每一段信息均是段首若干1,剩余若干0表示这种颜色有多少个 于是我们不难想到莫队 答 ...

  9. 4.3.1 ThreadLoacl简单使用

    我们都知道  SimpleDateFormat 这个类是线程 不安全的,那么我下面的程序执行就会遇到问题 public class ParseDateDemo { private static fin ...

  10. CTE递归限制次数

    CTE可以用来取递归,网上资料很多,这里就不再叙述了,今天遇到的需求是要限制只取2级,然后加了个临时的lev with tree as(select [CustomerID],[CustomerNam ...