2017-03-02 155 views
2

我有两个表具有复合主键:如何创建复合外键的表,复合主键

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

我不明白了什么,我做错了

回答

5

复合外键要求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建立关系要容易理解,并且不易出错。举例来说,同样可以通过以下流利的配置来实现:

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

顺便说一句相同的复合材料的PK(而不是所有这些Key/Column(Order = ...)属性):

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

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

什么明确的答案! !试着接受:)你写的EventA是什么意思:“public virtual ICollection Events {get; set;}” – Songaila

+0

首先我试了1个var。我得到一个错误:类型'xxx.Event'属性'DocID1'上的ForeignKeyAttribute无效。在依赖类型'xxx.Event'上找不到导航属性“DocID1,DocID2”。名称值应该是有效的导航属性名称。 Goint尝试Fluent API – Songaila

+0

保持与Fluen API,更容易理解没有更多的错误。谢谢你 – Songaila