试图在MSSQL服务器中播种数据库。 'Id'列设置为identity。我不明白为什么EF需要'Id的数据:
public class Location
{
public int? Id { get; set; }
public string Name { get; set; }
public IList<Office> Offices { get; set; }
}
...流畅的API:
modelBuilder.Entity<Location>()
.HasKey(k => k.Id);
modelBuilder.Entity<Location>()
.Property(p => p.Id)
.UseSqlServerIdentityColumn()
.ValueGeneratedOnAdd();
modelBuilder.Entity<Location>()
.HasData(
new Location() { Name = "Sydney" },
new Location() { Name = "Melbourne" },
new Location() { Name = "Brisbane" }
);
...据我所知,如果服务器在插入时生成'Id'则不需要提供。为什么我收到有关不提供ID的消息...
我认为错误就在这里
public int? Id { get; set; }
ID不应该是可空的。
更新:我的意思是你应该写:
public int Id { get; set; }
问号使您的属性可以为空,但由于它是主键,因此它不能为空。
我在这里做了一个小小的例子:
using System.Collections.Generic;
namespace ConsoleApp2.Models
{
public class Location
{
public int Id { get; set; }
public string Name { get; set; }
public IList<Office> Offices { get; set; }
}
}
流利的Api
migrationBuilder.CreateTable(
name: "Locations",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
Name = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Locations", x => x.Id);
});
我可以毫无问题地添加新位置。
using ConsoleApp2.Models;
using System.Collections.Generic;
namespace ConsoleApp2
{
class Program
{
static void Main(string[] args)
{
MyDbContext _c = new MyDbContext();
List<Office> list = new List<Office>()
{
new Office()
{
OfficeName = "Reception"
}
};
Location l = new Location()
{
Name = "New York",
Offices = list
};
_c.Locations.Add(l);
_c.SaveChanges();
}
}
}
我使用.net核心2.1与EFcore 2.2.2。
我希望有所帮助。