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 ...
随机推荐
- 前向渲染路径细节 Forward Rendering Path Details
正向渲染路径细节 Forward Rendering Path Details Forward Rendering path renders each object in one or more pa ...
- 适配iOS10 调取系统打电话功能
[[UIApplication sharedApplication] openURL:[NSURL URLWithString: [NSString stringWithFormat:@"t ...
- Apache CloudStack Features
As a mature and turnkey Infrastructure-as-a-Service (IaaS) platform, Apache CloudStack has a compreh ...
- GitLab服务器IP地址修改
gitlab安装介绍:https://about.gitlab.com/downloads/#centos7 刚搭建好的gitlab在GitLab上新建一个项目test_gitlab,刚开始仓库地址是 ...
- python切片、列表解析、元组
1.列表解析 test = [x**2 for x in range(1,11)] 2.切片 test1 = ["a","b","c",&q ...
- strerror线程安全分析
导读 strerror是否线程安全了? 1 errno是否线程安全? 1 附1:strerror源码 2 附2:__strerror_r源码 2 strerror是否线程安全了? 答案是NO,但它有个 ...
- .NET基础 (06)面向对象的实现
面向对象的实现1 C#中类可以有多个父类.可以实现多个接口吗2 简述C#中重写.重载和隐藏的概念3 为什么在构造方法中调用虚方法会导致问题4 在C#中如何声明一个类不能被继承 面向对象的实现 1 C# ...
- 编写高质量代码改善C#程序的157个建议——建议95:避免在构造方法中调用虚成员
建议95:避免在构造方法中调用虚成员 在构造方法中调用虚方法会带来一些意想不到的错误,虽然这种方法不常见,但还是需要注意这类陷阱. static void Main() { American amer ...
- Memory Analysis Part 1 – Obtaining a Java Heapdump
转自: https://blog.codecentric.de/en/2008/07/memory-analysis-part-1-obtaining-a-java-heapdump/ For tro ...
- Alpha冲刺(七)
Information: 队名:彳艮彳亍团队组长博客:戳我进入作业博客:班级博客本次作业的链接 Details: 组员1(组长)柯奇豪 过去两天完成了哪些任务 改用更易用的springboot+myb ...