Foreign key pointing to Compound Key

◇◆丶佛笑我妖孽 提交于 2019-12-11 02:47:34

问题


I'm working on a POCO entities model on an existing database. One table has a compound key

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...
}

and a second table with no primary key, but 2 properties referencing the compound key of Table1.

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...
}

QUESTION Is possible to map this Association using DataAnnotations? If so, How?


回答1:


Yes, you can define the compound foreign key with data annotations:

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...
}

Or alternatively:

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...
}

But the real problem is that your Table2 has no primary key which is required by Entity Framework. I don't think that there is any workaround to solve this problem - other than adding a primary key to the table.



来源:https://stackoverflow.com/questions/7986971/foreign-key-pointing-to-compound-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!