如何使用fluent API将子类的属性设置为主键
本文关键字:设置 属性 子类 何使用 fluent API | 更新日期: 2023-09-27 18:06:47
这是我的模型:
public class RepoDocument
{
public DocumentRecord Document { get; set; }
public string Title { get; set; }
public string Path { get; set; }
}
这是子类的定义:
public class DocumentRecord
{
public Guid Id { get; set; }
public string Name { get; set; }
// ... Other fields here...
}
我需要什么
我想把Id
作为RepoDocument
模型的主键。
我在数据库上下文中使用以下代码:
public class DocumentsContext : DbContext
{
public DocumentsContext()
: base("name=DbConnectionString")
{
}
public DbSet<RepoDocument> DocumentsTable { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<RepoDocument>().HasKey<Guid>(c => c.Document.Id);
}
}
问题
但是,当我在Package Manager控制台中运行add-migration
时,我会收到以下错误:
属性表达式"c=>c.Document.Id"无效。表达式应表示一个属性:C#:"t=>t.MyProperty"VB.Net:"Function(t(t.MyProperty'。指定多个属性时,请使用匿名类型:C#:"t=>new{t.MyProperty1,t.MyProperty2}"VB.Net:"Function(t。
问题
如何使用fluent API将模型的子类的属性设置为数据库的主键?
您的问题不正确。您应该使用继承。
public abstract class RepoDocument
{
public Guid Id { get; set; }
public string Title { get; set; }
public string Path { get; set; }
}
public class Document : RepoDocument
{
public string Name { get; set; }
// ... Other fields here...
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<RepoDocument>().ToTable("RepoDocument");
modelBuilder.Entity<Document>().ToTable("DocumentRecord");
}
我想,如果你的子类(顺便说一句,我第一次读到子类作为子类(被用作实体,你就不能了——它将存储在单独的表中,但在这种情况下,你的RepoDocument
将没有键。
我不确定,如果可能的话,你是否会把DocumentRecord
注册为ComplexType
,但你可以试试。在这种情况下,它将存储在同一个表中,所以听起来是可能的。
您可以为配置创建单独的类型,然后将其添加到OnModelCreating
中。
public class DocumentRecordConfiguration: ComplexTypeConfiguration<DocumentRecord>
{
public DocumentRecordConfiguration()
{
/* use fluent api here */
}
}