Arturo Martinez
Arturo Martinez

Reputation: 2583

Foreign key pointing to Compound Key

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?

Upvotes: 2

Views: 241

Answers (1)

Slauma
Slauma

Reputation: 177133

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.

Upvotes: 3

Related Questions