【问题标题】:Entity Framework Core: combined primary key through navigation property [duplicate]Entity Framework Core:通过导航属性组合主键[重复]
【发布时间】:2021-02-10 08:03:10
【问题描述】:

给出以下类:

public class Person{
    public int ID { get; set;}
    public string Name { get; set;}
    public List<Parentship> parentChildRelations { get; set; }
}

public class Parentship{
    public Person Parent { get; set; }
    public Person Child { get; set; }
    public string RelationshipType { get; set; }
    public Datetime date { get; set; }

使用 Entity Framework Core(代码优先),我想将其映射到以下表格:

表人:

ColumnName DataType Primary Key Foreign Key
ID int YES NO
Name varchar(max) NO NO

表亲子关系:

ColumnName DataType Primary Key Foreign Key
ParentID int YES YES
ChildID int YES YES
Type int NO NO
Date datetime NO NO

因此表Parentship 有一个复合主键(ParentIDChildID),其中这些列本身是表Person 的外键。

我尝试了类似的方法,但它不起作用,因为它在 PM 控制台中给出了以下错误消息:“属性 'Parentship.Parent' 的类型为 'Person',当前数据库提供程序不支持。更改属性 CLR 类型,或使用“[NotMapped]”属性或使用“OnModelCreating”中的“EntityTypeBuilder.Ignore”忽略该属性。”。 有人知道如何通过 Fluent API 解决这个问题吗?

modelBuilder.Entity<Parentship>()
    .HasKey(p => new { ParentID = p.Parent.ID, ChildID = p.Child.ID });

【问题讨论】:

  • @GertArnold:见编辑。

标签: c# entity-framework-core foreign-keys composite-primary-key ef-fluent-api


【解决方案1】:

请尝试添加索引值并将其设置为非聚集索引

entity.HasIndex(p => new { p.Parent.ID, p.Child.ID})
                    .HasName("some_name_for_index")
                    .ForSqlServerIsClustered(false);

【讨论】:

  • 请在发布前测试代码。这是无效的。
猜你喜欢
  • 2017-01-01
  • 2021-05-17
  • 1970-01-01
  • 2023-03-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多