【发布时间】:2019-06-01 04:39:21
【问题描述】:
我需要在实体框架中创建复合键。
我的基类键是“Guid”,我希望学生类中有一些独特的东西,比如可以读取的“ID”。像“STUD01”,它确实需要可读的唯一数据。
[NotMapped]
public class BaseEntity
{
public Guid Key { get; set; }
public DateTime? DateCreated { get; set; }
public string UserCreated { get; set; }
public DateTime? DateModified { get; set; }
public string UserModified { get; set; }
}
这是我的Student 课程
public class Student : BaseEntity
{
public string Id { get; set; }
public string Name { get; set; }
}
这是我的上下文类
public class SchoolContext: DbContext
{
public LibraContext(DbContextOptions<SchoolContext> options)
: base(options)
{ }
public DbSet<Student> Students { get; set; }
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<BaseEntity>().Property(x => x.DateCreated).HasDefaultValueSql("GETDATE()");
modelBuilder.Entity<BaseEntity>().Property(x => x.DateModified).HasDefaultValueSql("GETDATE()");
//here is my composite key
modelBuilder.Entity<Student>().HasKey(c => new { c.Key, c.Id });
}
我已运行以下迁移命令来创建脚本和更新数据库
Add-Migration -Name "InitialMigration" -Context "SchoolContext"
我得到这个错误:
无法在“学生”上配置密钥,因为它是派生类型。必须在根类型“BaseClass”上配置密钥。如果您不打算将“BaseClass”包含在模型中,请确保它不包含在上下文的 DbSet 属性中、在对 ModelBuilder 的配置调用中引用或从包含的类型的导航属性中引用在模型中。
如何实现?
我正在使用 ASP.NET Core 2.1
【问题讨论】:
-
modelBuilder.Entity
调用意味着将有一个名为 BaseTable 的表,必须在其上定义所有关键属性。您可能的意思是调用 modelBuilder.Types API。
标签: c# entity-framework asp.net-core migration