开发者

EF Code-First Composite "Navigation" Key

I've searched the already answered questions but found no answer to my problem. Shame on me.

I have this situation:

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}", ErrorMess开发者_高级运维age = "ID must be in ISO 639 standard")] 
    public string ID { get; set; }

    public string Country { get; set; }

    public string Language { get; set; }
}

But I can't get this to work. EF says that "RegionalInfo has no Key defined".

To be short, I'm trying to make a composite key on this class "RegionalInfo" that includes The Content.GUID and the Region.ID.

For every single UNIQUE Content in the Contents table, many "Translations" will exist in the RegionalInfo table.


I make the assumption your using a DbContext. Under that assumption you should define your keys in the RegionalInfo class like so

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

and in your context class you do the following:

    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);
    }

That should do the trick

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜