EF Code-First复合“导航”键

时间:2011-08-31 17:48:14

标签: c# asp.net-mvc-3 entity-framework-4.1

我搜索了已经回答的问题,但没有找到我的问题的答案。对我感到羞耻。

我遇到这种情况:

public class Content
{
    [Key]
    [StringLength(36, ErrorMessage="Must have 36 characters")]
    [Required(ErrorMessage="Must have a unique GUID")]
    public string GUID { get; set; }

    public virtual ICollection<RegionalInfo> RegionalInfo { get; set; }
}

public class RegionalInfo
{
    [Key]
    public virtual Content Content { get; set; }

    [Key]
    public virtual Region Region { get; set; }
}

public class Region
{
    [Key]
    [StringLength(5, ErrorMessage="ID must have 5 characters")]
    [Required]
    [RegularExpression(@"[a-z]{2}-[A-Z]{2}", ErrorMessage = "ID must be in ISO 639 standard")] 
    public string ID { get; set; }

    public string Country { get; set; }

    public string Language { get; set; }
}

但我不能让这个工作。 EF表示“RegionalInfo没有定义密钥”。

简而言之,我正在尝试在包含The Content.GUID和Region.ID的此类“RegionalInfo”上创建一个复合键。

对于Contents表中的每个UNIQUE内容,RegionalInfo表中将存在许多“Translations”。

1 个答案:

答案 0 :(得分:2)

我假设你使用DbContext。在这种假设下,您应该在RegionalInfo类中定义您的密钥,如此

public class RegionalInfo
{
    [Key]
    public String ContentId { get; set; }
    public virtual Content Content { get; set; }

    [Key]
    public string RegionId { get; set; }
    public virtual Region Region { get; set; }
}

并在您的上下文类中执行以下操作:

    protected override void OnModelCreating(System.Data.Entity.DbModelBuilder modelBuilder)
    {
        // Composite key definition
        modelBuilder.Entity<RegionalInfo>().HasKey(x => new { x.ContentId, x.RegionId });
        // And if I remember correctly this was required in order to do
        // var x = contentObject.RegionalInfo.Where(....) stuff
        modelBuilder.Entity<RegionalInfo>().HasRequired<Content>(x => x.Content).WithMany(x => x.RegionalInfo).HasForeignKey(x => x.ContentId);
    }

应该做的伎俩