文档菜单
文档首页
/ / /
EF Core 提供程序
/

配置 EF Core 提供程序

本页内容

  • 创建 POCO
  • 创建数据库上下文类
  • 使用 MongoDB
  • 示例

在本指南中,您将学习如何配置应用程序以使用 MongoDB Entity Framework Core 提供程序。有关如何设置新项目和安装 EF Core 提供程序的信息,请参阅快速入门.

创建Plain old CLR/Class object,或称为 POCO,作为您实体的模型。POCO 是一个简单的类对象,不继承任何框架特定基类或接口的功能。

以下代码示例展示了如何创建代表客户的 POCO

public class Customer
{
public ObjectId Id { get; set; }
public String Name { get; set; }
public String Order { get; set; }
}

提示

要了解更多关于 POCO 的信息,请参阅 .NET/C# 驱动器文档中的 POCO 指南

要开始使用 Entity Framework Core,创建一个继承自 DBContext 的上下文类。DbContext 派生类实例表示一个数据库会话,并用于查询和保存您的实体实例。

DBContext类公开了DBSet属性,这些属性指定了在使用该上下文时可以与之交互的实体。

以下示例创建了一个从DBContext派生类的实例,并将Customer对象指定为DBSet属性。

public class MyDbContext : DbContext
{
public DbSet<Customer> Customers { get; init; }
public MyDbContext(DbContextOptions options)
: base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Customer>().ToCollection("customers");
}
}

前面的代码示例覆盖了OnModelCreating()方法。覆盖OnModelCreating()方法允许您指定模型及其属性的配置详细信息。此示例使用ToCollection()方法指定应用程序中的Customer实体映射到MongoDB中的customers集合。

一旦创建了DBContext类,就构建一个DbContextOptionsBuilder对象,并调用其UseMongoDB()方法。此方法接受两个参数:一个MongoClient实例以及存储您正在处理的集合的数据库的名称。

UseMongoDB()方法返回一个DbContextOptions对象。将此对象的Options属性传递给您的DBContext类的构造函数。

以下示例显示了如何以这种方式构建DBContext对象。

var mongoClient = new MongoClient("<Your MongoDB Connection URI>");
var dbContextOptions =
new DbContextOptionsBuilder<MyDbContext>().UseMongoDB(mongoClient, "<Database Name");
var db = new MyDbContext(dbContextOptions.Options);

提示

创建MongoClient

当使用EF Core提供程序时,您可以在MongoDB .NET/C#驱动程序中调用方法。前面的示例使用.NET/C#驱动程序的MongoClient()方法创建一个连接到MongoDB实例的MongoDB客户端。

有关使用MongoDB .NET/C#驱动程序连接到MongoDB的更多信息,请参阅.NET/C#驱动程序文档中的连接指南

以下代码示例展示了如何配置EF Core提供程序并将文档插入数据库

using Microsoft.EntityFrameworkCore;
using MongoDB.Bson;
using MongoDB.Driver;
using Microsoft.Extensions.Configuration;
using MongoDB.EntityFrameworkCore.Extensions;
var mongoClient = new MongoClient("<Your MongoDB Connection URI>");
var dbContextOptions =
new DbContextOptionsBuilder<MyDbContext>().UseMongoDB(mongoClient, "<Database Name>");
var db = new MyDbContext(dbContextOptions.Options);
// Add a new customer and save it to the database
db.Customers.Add(new Customer() { name = "John Doe", Order = "1 Green Tea" });
db.SaveChanges();
public class Customer
{
public ObjectId Id { get; set; }
public String Name { get; set; }
public String Order { get; set; }
}
public class MyDbContext : DbContext
{
public DbSet<Customer> Customers { get; init; }
public MyDbContext(DbContextOptions options)
: base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Customer>().ToCollection("customers");
}
}

返回

基础