实体框架尝试选择不存在的列

时间:2018-11-30 22:05:25

标签: entity-framework entity-framework-6

我正在使用Entity Framework 6.0,并定义了2个POCO映射到我的数据库:

[Table("PortfolioGroups")]
public class PortfolioGroup : AuditableEntity<int>
{
    [Column("Company_Id")]
    public int CompanyId { get; set; }

    [ForeignKey("CompanyId")]
    public Company Company { get; set; }

    public string Name { get; set; }
    public string Description { get; set; }

    public ICollection<PortfolioGroupItem> PortfolioGroupItems { get; set; }

    public PortfolioGroup()
    {
        PortfolioGroupItems = new Collection<PortfolioGroupItem>();
    }
}

和PortfolioGroupItem:

[Table("PortfolioGroupItems")]
public class PortfolioGroupItem : AuditableEntity<int>
{
    [Column("PortfolioGroup_Id")]
    public int PortfolioGroupId { get; set; }

    [ForeignKey("PortfolioGroupId")]
    public PortfolioGroup PortfolioGroup { get; set; }

    [Column("Trademark_Id")]
    public int? TrademarkId { get; set; }

    [ForeignKey("TrademarkId")]
    public Trademark.Trademark Trademark { get; set; }

    [Column("TrademarkRegistration_Id")]
    public int? TrademarkRegistrationId { get; set; }

    [ForeignKey("TrademarkRegistrationId")]
    public TrademarkRegistration TrademarkRegistration { get; set; }

    [Column("Domain_Id")]
    public int? DomainId { get; set; }

    [ForeignKey("DomainId")]
    public Domains.Domain Domain { get; set; }
}

但是-当我尝试查询PortfolioGroups时,实体框架出于某种原因尝试查询名为“ Trademark_Id”的字段-PortfolioGroup实体上不存在该字段:

Context.PortfolioGroups.SingleOrDefault(i => i.Id == id && i.CompanyId == companyId);

抛出: 无效的列名“ Trademark_Id”。

我在应用程序的其他位置使用了这种设置,没有任何问题。我根本无法找出为什么EF试图查询不在我实体中的列!

任何建议将不胜感激。我在这里尽头了。

谢谢大家! :)

1 个答案:

答案 0 :(得分:0)

问题是您在商标上添加了需要在投资组合组上使用外键的导航属性:

public class Trademark
{
    [Key]
    public int Id { get; set; }

    [MaxLength(250)]
    [Required]
    public string Name { get; set; }

    [MaxLength(150)]
    public string Filename { get; set; }

    public ICollection<PortfolioGroup> PortfolioGroups { get; set; }

    public Trademark()
    {
        PortfolioGroups = new Collection<PortfolioGroup>();
    }
}

EF期望PortfolioGorup拥有一个Trademark_ID列,以存储与一个商标相关联的PortfolioGroup。