Access MongoDB Data with Entity Framework 6
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.
- Open Visual Studio and create a new Windows Form Application. This article uses a C# project with .NET 4.5.
- Run the command 'Install-Package EntityFramework' in the Package Manger Console in Visual Studio to install the latest release of Entity Framework.
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><addname="MongoDBContext"connectionString="Offline=False;Server=MyServer;Port=27017;Database=test;User=test;Password=Password;"providerName="System.Data.CData.MongoDB"/></connectionStrings><entityFramework><providers>...<providerinvariantName="System.Data.CData.MongoDB"type="System.Data.CData.MongoDB.MongoDBProviderServices, System.Data.CData.MongoDB.Entities.EF6"/></providers><entityFramework></configuration></code>- Add a reference to System.Data.CData.MongoDB.Entities.EF6.dll, located in the lib -> 4.0 subfolder in the installation directory.
- Build the project at this point to ensure everything is working correctly. Once that's done, you can start coding using Entity Framework.
- 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.
usingSystem.Data.Entity;usingSystem.Data.Entity.Infrastructure;usingSystem.Data.Entity.ModelConfiguration.Conventions;classMongoDBContext : DbContext {publicMongoDBContext() { }protectedoverridevoidOnModelCreating(DbModelBuilder modelBuilder){// To remove the requests to the Migration History tableDatabase.SetInitializer<MongoDBContext>(null);// To remove the plural namesmodelBuilder.Conventions.Remove<PluralizingTableNameConvention>();}} - 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:
usingSystem.Data.Entity.ModelConfiguration;usingSystem.ComponentModel.DataAnnotations.Schema;[System.ComponentModel.DataAnnotations.Schema.Table("restaurants")]publicclassrestaurants {[System.ComponentModel.DataAnnotations.Key]publicSystem.String _id {get;set; }publicSystem.String borough {get;set; }} - Now that you have created an entity, add the entity to your context class:
publicDbSet<restaurants> restaurants {set;get; } - With the context and entity finished, you are now ready to query the data in a separate class. For example:
MongoDBContext context =newMongoDBContext();context.Configuration.UseDatabaseNullSemantics =true;var query = from lineincontext.restaurants select line;
Access MongoDB Data with Entity Framework 6的更多相关文章
- AppBox升级进行时 - 拥抱Entity Framework的Code First开发模式
AppBox 是基于 FineUI 的通用权限管理框架,包括用户管理.职称管理.部门管理.角色管理.角色权限管理等模块. 从Subsonic到Entity Framework Subsonic最早发布 ...
- Programming Entity Framework 翻译(2)-目录2-章节
How This Book Is Organized 本书组织结构 Programming Entity Framework, Second Edition, focuses on two ways ...
- 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 ...
- 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 ...
- Professional C# 6 and .NET Core 1.0 - 38 Entity Framework Core
本文内容为转载,重新排版以供学习研究.如有侵权,请联系作者删除. 转载请注明本文出处:Professional C# 6 and .NET Core 1.0 - 38 Entity Framework ...
- 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 ...
- Entity Framework 6连接Postgresql、SQLite、LocalDB的注意事项和配置文件
Postgresql Postgresql支持Code First的方式自动生成表,不过默认的模式是dbo而不是public,而且还可以自动生成自增主键. <?xml version=" ...
- 让EF飞一会儿:如何用Entity Framework 6 连接Sqlite数据库
获取Sqlite 1.可以用NuGet程序包来获取,它也会自动下载EF6 2.在Sqlite官网上下载对应的版本:http://system.data.sqlite.org/index.html/do ...
- Entity Framework使用Sqlite时的一些配置
前段时间试着用Entity Framework for Sqlite环境,发现了一些坑坑洼洼,记录一下. 同时试了一下配置多种数据库,包括Sqlite.Sql Server.Sql Server Lo ...
随机推荐
- ShadowVolume
[ShadowVolume] 1.z-pass 算法. z-pass 是 shadow volume 一开始的标准算法,用来确定某一个象素是否处于阴影当中.其原理是: Pass1:enable z-b ...
- Fog
[Fog] Fog parameters are controlled with Fog command. Fogging blends the color of the generated pixe ...
- sql设置字段默认值
alter table 表名 modify 字段名 default 默认值;
- Tsung测试之配置文件
Jabber配置: <?xml version="1.0"?> <!DOCTYPE tsung SYSTEM "/usr/local/tsung/sha ...
- java synchronized详解[转]
Java语言的关键字,当它用来修饰一个方法或者一个代码块的时候,能够保证在同一时刻最多只有一个线程执行该段代码. 一.当两个并发线程访问同一个对象object中的这个synchronized(this ...
- p4051 [JSOI2007]字符加密
传送门 分析 将字符串复制一遍然后直接求sa即可 代码 #include<iostream> #include<cstdio> #include<cstring> ...
- nltk 之 snowball 提取词干-乾颐堂
机器学习中很重要的应用场景就是机器自动分类,而分类的关键是词干提取.所以我们要用到snowball.下面说一下snowball 提取词干的两种方法. 两种方法: 方法一: >>> f ...
- [Jenkins] 执行SoapUI的task,设置邮件内容为HTML+CSS
设置邮件内容:Default Content <span style="font-family:verdana;font-size:16px;color:black;font-weig ...
- 黑盒测试实践-任务进度-Day04
任务进度11-29 使用工具 selenium 小组成员 华同学.郭同学.穆同学.沈同学.覃同学.刘同学 任务进度 经过了前两天的学习任务的安排,以下是大家的任务进度: 华同学(任务1) 1.和其他小 ...
- 白盒测试实践项目(day4)
华中科技大学教材订购系统 代码评审会议纪要 与会人员: 胡俊辉.杨瑞丰.汪鸿.张颖.李建文 评审标准: 此次代码评审会议,我们小组选用了阿里巴巴Java开发手册对代码进行评审. 会议过程: 1:周末下 ...