mjuk
mjuk

Reputation: 337

Invalid inside an 'Include' operation, since it does not represent a property access: 't => t.MyProperty'

I'm getting the following error on an Entity Framework Core MVC app. Can anyone help with why? I'm including simplified versions of my Models below.

InvalidOperationException: The expression 'b.BrandId' is invalid inside an 'Include' operation, since it does not represent a property access: 't => t.MyProperty'. To target navigations declared on derived types, use casting ('t => ((Derived)t).MyProperty') or the 'as' operator ('t => (t as Derived).MyProperty'). Collection navigation access can be filtered by composing Where, OrderBy(Descending), ThenBy(Descending), Skip or Take operations.

I have a Products table and a Brands table. Brands are unique and Products can only have one Brand, but there can be many Products for a single Brand.

The Products model and Brand model:

public class Product
{
    public int Id { get; set; } 
    public string Name { get; set; } 
    public int BrandId { get; set; } 
    
    public virtual Brand Brand { get; set; }

    public Product()
    {
        Brand = new Brand();
    }
}

public class Brand
{
    public int BrandId { get; set; }
    
    public string BrandName { get; set; }
}

Then in my ProductsController this is what throws the above error. The include Brand part is so I can show the BrandName on my Index page and it is there that the error can be traced to:

// GET: Products
public async Task<IActionResult> Index()
{
    return View(await _context.Products.Include(b => b.Brand)
        .OrderByDescending(d => d.CreatedDate)
        .AsNoTracking().ToListAsync());
}

Upvotes: 10

Views: 32212

Answers (2)

G Clovs
G Clovs

Reputation: 3102

I just wanted to share my solution with a similar error on a ICollection

My Error

// My error here was my collection, because it is a field

public ICollection<Product> Products = new List<Product>();

Solution

// I just had to make it as a Property

public ICollection<Product> Products { get; set; } = new List<Product>();

Took me a while to find my little error... But now the error is really explicit for me

since it does not represent a property access: 't => t.MyProperty'.

Upvotes: 9

Serge
Serge

Reputation: 43880

Your classes are not properly configured and don't create any constructor:

public class Product
{
    [Key]
    public int Id { get; set; } 
    public string Name { get; set; } 

    public int BrandId { get; set; } 
     [ForeignKey(nameof(BrandId))]
     [InverseProperty("Products")]
    public virtual Brand Brand { get; set; }
}

public class Brand
{
    [Key]
    public int Id { get; set; }
    public string Name { get; set; }

    [InverseProperty(nameof(Product.Brand))]
    public virtual  ICollection<Product> Products{ get; set; }
}

Upvotes: 6

Related Questions