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. mysql默认字符编码设置教程:my.ini设置字符编码

    在mysql的安装目录下找到my.ini,如果没有就把my-medium.ini复制为一个my.ini即可. 打开my.ini以后, [client] default-character-set=ut ...

  2. Codeforces 667C DP

    题意:给你一个字符串,这个字符串的构造方法如下:先选择一个长度大于4的前缀,然后每次向字符串尾部添加一个长度为2或者长度为3的后缀,不能添加连续的相同的后缀,问可能的后缀有哪些?并按字典序输出去. 思 ...

  3. SUSE制作ISO源

    These commands have been tested on openSUSE 11. First create a directory where you will store your I ...

  4. spring4-3-AOP-基于配置文件

    1.建立业务类和切面类 2.在配置文件中配置bean 引入命名空间:

  5. Zookeeper使用--开源客户端

    一.ZkClient ZkClient是在Zookeeper原生API接口之上进行了包装,是一个更易用的Zookeeper客户端,其内部还实现了诸如Session超时重连.Watcher反复注册等功能 ...

  6. code1225 搭积木

    题目分析:将当前层定义为第h层,共用了n块积木,本层积木数为m,f(h,n,m) 那么可以扩展数两种状态:f(h-1,n-m,m-1),f(h-1,n-m,m+1) 直接搜索可能的数据达到h^m,超时 ...

  7. [GO]结构体成员的使用:普通变量

    package main import "fmt" func main() { type student struct { id int name string sex byte ...

  8. Word2013写CSDN博客

    目前大部分的博客作者在用Word写博客这件事情上都会遇到以下3个痛点: 1.所有博客平台关闭了文档发布接口,用户无法使用Word,Windows Live Writer等工具来发布博客.使用Word写 ...

  9. 机器学习及其matlab实现—从基础到实践

    第1周 MATLAB入门基础 第2周 MATLAB进阶与提高 第3周 BP神经网络 第4周 RBF.GRNN和PNN神经网络 第5周 竞争神经网络与SOM神经网络 第6周 支持向量机(Support ...

  10. .NET基础 (05)内存管理和垃圾回收

    内存管理和垃圾回收1 简述.NET中堆栈和堆的特点和差异2 执行string abc="aaa"+"bbb"+"ccc"共分配了多少内存3 ...