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
>
<
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
>
- 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.
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>();
}
}
- 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 {
get
;
set
; }
public
System.String borough {
get
;
set
; }
}
- Now that you have created an entity, add the entity to your context class:
public
DbSet<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 =
new
MongoDBContext();
context.Configuration.UseDatabaseNullSemantics =
true
;
var query = from line
in
context.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 ...
随机推荐
- Transform & Physics
[Transform & Physics] 1.Space.Unity定义了Space枚举值,此值如下: 通常通过Space.World.Space.Self来区别一个Vector是按世界坐标 ...
- TCP与UDP与HTTP协议
http:是用于www浏览的一个协议.tcp:是机器之间建立连接用的到的一个协议. 1.TCP/IP是个协议组,可分为三个层次:网络层.传输层和应用层.在网络层有IP协议.ICMP协议.ARP协议.R ...
- tomcat使用log4j管理日志
1.JDK+tomcat环境 参考:http://www.cnblogs.com/zzzhfo/p/6444029.html 2.下载相关软件 log4j下载地址 http://www.apache ...
- Openssl rand命令
一.简介 rand命令用来产生伪随机字节,随机数字产生器需要一个seed,在没有/dev/srandom系统下的解决方法是自己做一个~/.rnd文件 二.语法 openssl rand [-out f ...
- C++代码静态分析工具splint
1.引言 最近在项目中使用了静态程序分析工具PC-Lint, 体会到它在项目实施中带给开发人员的方便.PC-Lint是一款针对C/C++语言.windows平台的静态分析工具,FlexeLint是针对 ...
- grpc-java 生成代码路径设置
grpc-java 生成代码路径设置 <plugin> <groupId>org.xolstice.maven.plugins</groupId> <arti ...
- mysql 存储过程学习(总)
#一.存储过程和存储函数的创建案例 CREATE PROCEDURE myprocedure(in a int,in b int ,OUT c INT) BEGIN set c=a+b; end; c ...
- Inno Setup创建快捷方式跟快速运行栏快捷方式
[Tasks] Name: "desktopicon"; Description: "{cm:CreateDesktopIcon}"; GroupDescrip ...
- not in查询不出数据问题
select ID from SmartCustomer where ID not in (select distinct CustomerID from SmartPromoter where Cu ...
- 【转载】rabbitmq的发布确认和事务
地址:https://my.oschina.net/lzhaoqiang/blog/670749 摘要: 介绍confirm的工作机制.使用spring-amqp介绍事务以及发布确认的使用方式.因为事 ...