gpt4 book ai didi

c# - 指向复合键的外键

转载 作者:行者123 更新时间:2023-11-30 22:34:06 26 4
gpt4 key购买 nike

我正在现有数据库上开发 POCO 实体模型。一张表有复合键

public class Table1
{
[Key]
public virtual int Key1 {get; set;}

[Key]
public virtual int Key2 {get; set;}

public virtual ICollection<Table2> Tables2 {get; set;}

//more properties here...
}

第二个表没有主键,但有 2 个属性引用表 1 的复合键。

public class Table2
{
public virtual int Key1 {get; set;}

public virtual int Key2 {get; set;}

[InverseProperty("Tables2")]
public virtual Table1 Table1 {get; set;}

//more properties here...
}

问题 是否可以使用 DataAnnotations 映射此关联?如果是,怎么做?

最佳答案

是的,您可以使用数据注释定义复合外键:

public class Table2
{
[ForeignKey("Table1"), Column(Order = 1)]
public virtual int Key1 {get; set;}

[ForeignKey("Table1"), Column(Order = 2)]
public virtual int Key2 {get; set;}

[InverseProperty("Tables2")]
public virtual Table1 Table1 {get; set;}

//more properties here...
}

或者:

public class Table2
{
public virtual int Key1 {get; set;}

public virtual int Key2 {get; set;}

[InverseProperty("Tables2")]
[ForeignKey("Key1, Key2")]
public virtual Table1 Table1 {get; set;}

//more properties here...
}

但真正的问题是您的 Table2 没有 Entity Framework 要求的主键。我不认为有任何解决方法可以解决此问题 - 除了向表中添加主键。

关于c# - 指向复合键的外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7986971/

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