gpt4 book ai didi

entity-framework-6 - 如何使用复合主键为表创建复合外键

转载 作者:行者123 更新时间:2023-12-04 00:14:06 24 4
gpt4 key购买 nike

我有两个带有复合主键的表:

public class Event
{
[Key]
[Column(Order = 1)]
public string ID1 { get; set; }

[Key]
[Column(Order = 2)]
public int ID2 { get; set; }
public DateTime EventDate { get; set; }
public string DocID1 { get; set; }
public int DocID2 { get; set; }

}

public class EventDocument
{
[Key]
[Column(Order = 1)]
public string ID1 { get; set; }
[Key]
[Column(Order = 2)]
public int ID2 { get; set; }

public string Name { get; set; }
public string SurName { get; set; }
public string Number { get; set; }

public virtual ICollection<Event> Events { get; set; }
}

我需要在 Event 表上创建一个复合外键到 EventDocument

我尝试过像这样创建 FK

类事件:

[ForeignKey("DocID1")]
[Column(Order = 0)]
public string DocID1 { get; set; }

[ForeignKey("DocID2")]
[Column(Order = 1)]
public string DocID2 { get; set; }

但我得到一个错误:

The property 'DocID1' cannot be configured as a navigation property. The property must be a valid entity type and the property should have a non-abstract getter and setter. For collection properties the type must implement ICollection where T is a valid entity type."}

我不明白我做错了什么

最佳答案

复合外键需要 ForeignKey要应用于导航属性的属性,指定以逗号分隔的外键属性名称列表:

If you add the ForeignKey attribute to a foreign key property, you should specify the name of the associated navigation property. If you add the ForeignKey attribute to a navigation property, you should specify the name of the associated foreign key(s). If a navigation property has multiple foreign keys, use comma to separate the list of foreign key names.

由于您在 Event 类中没有导航属性,因此应将其应用于 EventDocument 类中的相应导航属性:

[ForeignKey("DocID1, DocID2")]
public virtual ICollection<Event> Events { get; set; }

问题应该得到解决。

但我个人发现与 Fluent API 建立关系更容易理解且不易出错。例如,同样可以通过以下 fluent 配置实现:

modelBuilder.Entity<EventDocument>()
.HasMany(e => e.Events)
.WithRequired() // or .WithOptional()
.HasForeignKey(e => new { e.DocID1, e.DocID2 });

复合 PK 的相同 btw(而不是所有这些 Key/Column(Order = ...) 属性):

modelBuilder.Entity<Event>()
.HasKey(e => new { e.ID1, e.ID2 });

modelBuilder.Entity<EventDocument>()
.HasKey(e => new { e.ID1, e.ID2 });

关于entity-framework-6 - 如何使用复合主键为表创建复合外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42556676/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com