这是我的模型:
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 Console 中运行 add-migration
时出现以下错误:
The properties expression 'c => c.Document.Id' is not valid. The expression should represent a property: C#: 't => t.MyProperty' VB.Net: 'Function(t) t.MyProperty'. When specifying multiple properties use an anonymous type: C#: 't => new { t.MyProperty1, t.MyProperty2 }' VB.Net: 'Function(t) New With { t.MyProperty1, t.MyProperty2 }'.
问题
如何使用 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");
}
关于c# - 如何使用 Fluent API 将子类的属性设置为主键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31860623/