Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework attempting to select non-existing column

I'm using Entity Framework 6.0 and have defined 2 POCO's to map to my database:

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

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

However - when I attempt to query the PortfolioGroups, Entity Framework for some reason attempts to query a field named "Trademark_Id" - which doesn't exist on the PortfolioGroup entity:

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

Throws: Invalid column name 'Trademark_Id'.

I've used this kind of setup other places in my application without any problems. I simply cannot find out why EF is trying to query a column that's not in my entity!

Any suggestions would be greatly appreciated. I'm at the end of my rope here.

Thanks guys! :)

like image 415
InversionDK Avatar asked Dec 06 '25 18:12

InversionDK


1 Answers

The problem is that you've added a Navigation Property on Trademark that requires a Foreign Key on Portfolio Group:

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 expects PortfolioGorup to have a Trademark_ID column to store which PortfolioGroups are associated with a Trademark.

like image 165
David Browne - Microsoft Avatar answered Dec 11 '25 08:12

David Browne - Microsoft



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!