FK和主键 - 实体框架

时间:2015-08-29 23:56:01

标签: c# entity-framework key code-first composite-primary-key

我有两张桌子。我想声明SiteId(以及Username)作为主键。

[Key][Key,ForeignKey("SiteId)]等方法效果不佳。

public class SiteTable
{
    //SITE ID
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [Key]
    public int SiteId { get; set; }

    // NAVIGATION PROPERTY 
    public virtual ICollection<UserTable> Users { get; set; }
}

public class UserTable
{
    //USERNAME
    [Key]
    public string Username { get; set; }

    //FK
    public int SiteId { get; set; }

    //NAVIGATION PROPERTY        
    public virtual SiteTable Sites { get; set; }
}

1 个答案:

答案 0 :(得分:1)

尝试定义您的复合键:

public class UserTable
{
   [Key,Column(Order = 0)]
   public string Username { get; set; }

   [Key,Column(Order = 1)]
   public int SiteId { get; set; }

   public virtual SiteTable Site { get; set; }
}