外键指向复合键 [英] Foreign key pointing to Compound Key

查看:230
本文介绍了外键指向复合键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我工作的一个POCO实体模型中的现有数据库。
的表具有复合键

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

和第二个表没有主键,但2个属性参照表1的复合键。

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

< STRONG>问题可以使用地图这DataAnnotations协会?
。如果是这样,如何

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

推荐答案

是的,你可以定义复合外键与数据的注解:

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

或者:

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

但真正的问题是,你的表2 有一个由实体框架不需要主键。我不认为有任何解决办法来解决这个问题 - 不是增加一个主键表中其他

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.

这篇关于外键指向复合键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆