如何修复System.InvalidOperationException错误?

时间:2019-10-01 15:23:21

标签: c# entity-framework

我正在尝试使用Entity Framework联接两个表,但出现System.InvalidOperationException错误。错误消息是:

  

属性“ MasterCompany”不是实体类型“ UnitOfMeasure”的导航属性。 “ include(string)”方法只能与“。”一起使用。导航属性名称的分隔列表。

我不确定为什么要扔它。

其他尝试:

  1. 我还尝试在public virtual MasterCompany MasterCompany { get; set; }中添加UnitOfMeasure,但是会抛出Invalid column error
  2. 还为[Key]MasterCompany表中添加了MasterCompanyId
  3. 但是这两个更改都引发Invalid column name 'IsDeleted'.错误。

DAL模型:

public class ApplicationDbContext : IdentityDbContext<ApplicationUser, ApplicationRole, string>
{
  public DbSet<UnitOfMeasure> UnitOfMeasure { get; set; }
  public DbSet<MasterCompany> MasterCompany { get; set; }
}

public class UnitOfMeasure : PasBase, IAudit
{
    [Key]
    public long UnitOfMeasureId { get; set; }
    public string Description { get; set; }
    public string ShortName { get; set; }
    public string Memo { get; set; }
    public string Standard { get; set; }
    // [ForeignKey("MasterCompanyId")]
    public Int32 MasterCompanyId { get; set; }
    public bool IsActive { get; set; }
    public bool IsDeleted { get; set; }
    [NotMapped]
    public string UploadStatus { get; set; }
    [ForeignKey("MasterCompanyId")]
    public virtual MasterCompany MasterCompany { get; set; }
}

public class MasterCompany:AuditableEntity
{
    public int MasterCompanyId { get; set; }
    public string CompanyName { get; set; }
    public string TaxId { get; set; }
    public string EmailAddress { get; set; }
    public string Address { get; set; }
    public bool? IsActive { get; set; }
}

存储库:

private ApplicationDbContext _appContext => (ApplicationDbContext)_context;

public IEnumerable<DAL.Models.UnitOfMeasure> getUnitOfMeasureData()
{
    return _appContext.UnitOfMeasure
        .Include("MasterCompany")
        .Where(c => c.IsDeleted == false || c.IsDeleted == null)
        .OrderByDescending(c => c.UnitOfMeasureId)
        .ToList();
}

1 个答案:

答案 0 :(得分:2)

您需要在类MasterCompany中添加UnitOfMeasure属性

public class UnitOfMeasure : PasBase, IAudit
{
    [Key]
    public long UnitOfMeasureId { get; set; }
    public string Description { get; set; }
    public string ShortName { get; set; }
    public string Memo { get; set; }
    public string Standard { get; set; }
    public Int32 MasterCompanyId { get; set; }
    [ForeignKey("MasterCompanyId")]
    public MasterCompany MasterCompany { get; set; }
    public bool IsActive { get; set; }
    public bool IsDeleted { get; set; }
    [NotMapped]
    public string UploadStatus { get; set; }
}