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 ...
随机推荐
- 114. Flatten Binary Tree to Linked List (Stack, Tree; DFS)
Given a binary tree, flatten it to a linked list in-place. For example, Given 1 / \ 2 5 / \ \ 3 4 6 ...
- Spket,eclipse下安装Spket插件,格式化js
点击菜单 Help => Install New SoftWare => add 如图 name框输入:Skept Location框输入:http://www.agpad.com/upd ...
- 微信小程序文档里看不到的小Tips
前几天折腾了下.然后列出一些实验结果,供大家参考. 0. 使用开发工具模拟的和真机差异还是比较大的.也建议大家还是真机调试比较靠谱. 1. WXML(HTML) 1.1 小程序的WXML没有HTML的 ...
- Linux 下启动两个tomcat
Linux 下启动两个tomcat 闲来无事学习nginx,想要配置个load balance.可是先决条件是:得有两个web容器.两个电脑是不用想了.只能想办法在一个机器上启动两个tomcat.原以 ...
- telnet客户端模拟浏览器发送请求
telnet 客户端 telnet客户端能够发出请求去连接服务器(模拟浏览器) 使用telnet之前,需要开启telnet客户端 1.进入控制面板 2.进入程序和功能,选择打开或关闭windows功能 ...
- Linux发送邮件
以下是自己收集的实用Linux下简单配置外部邮箱发送邮件的方法: 1.配置/etc/mail.rc,使用mail命令 # vim /etc/mail.rc ###调用外部邮箱 set from=t ...
- MicroRNA 详解
MicroRNA研究历史和方法 Views 88 1Report
- django model ValueQuerySet QuerySet 转换成JSON
这里我有4个字段需要使用外键,那么在调取数据的时候就可以使用两个'_'进行调取,当然条件必须需要从前端传进来 models.py class HostInfo(models.Model): host_ ...
- javascrip总结42:属性操作案例: 点击盒子,改变盒子的位置和背景颜色
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8& ...
- CodeForces 339C Xenia and Weights(暴力求解DFS)
题意:给定 1-10的某几种砝码,给定的每种有无穷多个,然后放 m 个在天平上,要满足,相邻的两次放的砝码不能是同一种,然后是在天平两端轮流放,并且放在哪一个托盘上,那么天平必须是往哪边偏. 析:这个 ...