从一端定义关系有效,但从另一端定义它会导致错误

时间:2016-05-01 20:14:03

标签: c# entity-framework-core

为什么在OnModelCreating中调用base之后的第一行会导致错误?抛出的注释行会导致此错误:

表达式'x => value(Blog.Services.Db).ContentItems'不是有效的属性表达式。表达式应代表属性访问:'t => t.MyProperty”。 参数名称:propertyAccessExpression

    protected override void OnModelCreating(ModelBuilder mb)
    {
        base.OnModelCreating(mb);
        mb.Entity<ContentGroup>().HasMany(x => ContentItems).WithOne(x => x.ContentGroup).HasForeignKey(x => x.ContentGroupID);  // same effect as following line but throws an error
        //mb.Entity<ContentItem>().HasOne(x => x.ContentGroup).WithMany(x => x.ContentItems).HasForeignKey(x => x.ContentGroupID); // same effect as previous line but works

    }

contentGroup的:

public class ContentGroup
{
    public int ID { get; set; }
    public int SiteID { get; set; }
    public string Description { get; set; }
    public int Sequence { get; set; }
    public bool Active { get; set; }
    public virtual Site Site { get; set; }
    public virtual ICollection<ContentItem> ContentItems { get; set; }
}

ContentItem:

public class ContentItem
{
    public int ID { get; set; }
    public string ContentType { get; set; }
    public int ContentGroupID { get; set; }
    public DateTime? PublishDate { get; set; }
    public DateTime? LastModifyDate { get; set; }
    public string ChangeFrequency { get; set; }
    public decimal? Priority { get; set; }
    public bool Active { get; set; }
    public string Slug { get; set; }
    public string Title { get; set; }
    public string MenuText { get; set; }
    public string URI { get; set; }
    public string Abstract { get; set; }
    public string Icon { get; set; }
    public string Tags { get; set; }
    public bool AllowComments { get; set; }
    public virtual ICollection<Comment> Comments { get; set; }
    public virtual ContentGroup ContentGroup { get; set; }
    public virtual ICollection<MenuContentItem> MenuContentItems { get; set; }
}

1 个答案:

答案 0 :(得分:1)

在第一个语句中,HasForeignKey()方法反映到ContentGroup实体而不是ContentItem实体。 ContentGroup实体没有ContentGroupId属性,这就是它无效的原因。

<强>更新

  

表达式'x =&gt; value(Blog.Services.Db).ContentItems'不是有效的属性表达式。表达式应代表属性访问:'t =&gt; t.MyProperty”。参数名称:propertyAccessExpression

根据它发生的异常消息,因为在第一个语句中您有.HasMany(x => ContentItems)但它应该是.HasMany(x => x.ContentItems)