在“包含"操作中无效,因为它不代表属性访问权限:"t =>t.MyProperty' [英] Invalid inside an 'Include' operation, since it does not represent a property access: 't => t.MyProperty'

查看:165
本文介绍了在“包含"操作中无效,因为它不代表属性访问权限:"t =>t.MyProperty'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Entity Framework Core MVC应用程序上遇到以下错误.任何人都可以帮忙吗?我在下面包括了我的模型的简化版本.

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:表达式'b.BrandId'无效在包含"操作中,因为它不代表属性访问:"t =>t.MyProperty".定位在派生时声明的导航类型,请使用强制转换('t =>(((Derived)t).MyProperty')或'as'运算符('t =>(t等于Derived.MyProperty').集合导航可以通过组合Where,OrderBy(Descending),然后按(降序),跳过"或取"操作.

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.

产品模型和品牌模型:

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

然后在我的ProductsController中抛出以上错误.包括品牌部分是为了使我可以在索引页面上显示品牌名称,并且可以在其中找到错误:

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

推荐答案

您的类未正确配置,并且未创建任何构造函数:

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

这篇关于在“包含"操作中无效,因为它不代表属性访问权限:"t =&gt;t.MyProperty'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆