c# - 如何使用 Fluent API 将子类的属性设置为主键

标签 c# entity-framework ef-fluent-api

这是我的模型:

  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/

相关文章:

c# - 在 C# 中,是否需要调用基类构造函数?

c# - 调用 Facebook/Google+ 时 ExternalLogin 未命中

c# - 帮助理解 C# 优化

c# - Entity Framework 将字符串转换为 Int

.net - EF Fluent Api 可以设置最小长度吗?

c# - 使用linq to实体进行嵌套查询

c# - 将所有用户数据保存在 Forms 身份验证 cookie 中

c# - 在依赖类型上找不到导航属性

c# - 更改代码优先 Entity Framework 中的列名称?

c# - 在 EF 6 中找不到 HasOne