如何使用EF Core Cosmos提供程序与ASP.NET Core 3.1



遵循微软编写的这个简单的EF Core教程,一切都运行良好。学生可以创建、读取、更新和删除。

下面是尝试切换到Cosmos DB而不是SQL Server的步骤:

已安装Microsoft.EntityFrameworkCore.Cosmos包。

替换Startup.cs中的以下代码

// This block removed
services.AddDbContext<SchoolContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
// This block added
services.AddDbContext<SchoolContext>(options =>
options.UseCosmos(
"https://example.documents.azure.com:443/",
"Example primary key",
"EFCoreTest"
));

现在运行应用程序时,在尝试创建学生时返回以下错误:

NotSupportedException:实体类型'Student'上的'ID'没有值集,并且'int'类型的属性没有值生成器可用。要么在添加实体之前为属性设置一个值,要么为'int'类型的属性配置一个值生成器。

什么是正确的方式来使用Cosmos DB而不是SQL Server使用EF Core 3.1?

你有没有试过在你的上下文中设置这个,你可以覆盖onmodelcreating例如(x代表你的实体)

protected override void OnModelCreating(ModelBuilder modelBuilder) {
modelBuilder.Entity<x>().Property(t => t.Id).ValueGeneratedOnAdd(); }

当自动生成id时,添加

最新更新