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 ...
随机推荐
- 微信小程序相关三、css写小黄人
小程序上课第三天,因为今天院里有活动,所以没去上课,第四天上午又因为要召开入党转正大会,又耽误了一上午,下午去上课,要了资料.这两天讲了一些零零碎碎的东西,做的实例有上面这个小黄人 都是用的css,基 ...
- JAVA 定时器的三种方法
/** * 普通thread * 这是最常见的,创建一个thread,然后让它在while循环里一直运行着, * 通过sleep方法来达到定时任务的效果.这样可以快速简单的实现,代码如下: * @au ...
- Crack IDEA
使用破解补丁 Crack IDEA→在http://idea.lanyus.com/上可以找到最新的破解补丁,下载并放到软件的bin目录下 →更改bin目录下的两个文件:Idea.exe.vmopti ...
- TensorFlow全新的数据读取方式:Dataset API入门教程
TensorFlow.data : http://tech.ifeng.com/a/20171109/44752505_0.shtml Pytorch:https://ptorch.com/docs/ ...
- Hive入门学习随笔(二)
====使用Load语句执行数据的导入 --将操作系统上的文件student01.txt数据导入到t2表中 load data local inpath '/root/data/student01.t ...
- Part2_lesson1---arm家族大检阅
芯片(比如2440.6410.210等等)包含ARM核. 指令结构和ARM核有关系: ARM9对应指令架构版本ARMV4 ARM11对应指令架构版本ARMV6 cortex A8对应指令架构版本ARM ...
- OpenNIDataGet 获取点云数据
运行后,采集的数据保存到:E:\OpenCVData目录下的color和depth文件夹下.接下来要求参数:内参 外参 这些参数最好优化后使用精度高 如何得到+保存格式 yaml 保存文件格式: 1. ...
- document--文档中的操作,操作属性、操作样式、操作元素
---恢复内容开始--- document操作: 1.找元素 getE.. 2.操作内容 非表单:innerHtml 表单:value 3.操作属性 ...
- Appium常用API(一)
Appium作为当下一款移动应用的自动化测试工具,对于测试来说重要性不言可寓,废话不多说,下面总结下它常用的API: 1.contextscontexts(self): Returns the con ...
- js调试工具Console命令详解——转
一.显示信息的命令 <!DOCTYPE html> <html> <head> <title>常用console命令</title> < ...