【发布时间】:2021-02-16 18:00:07
【问题描述】:
我在 Entity Framework Core MVC 应用程序上收到以下错误。谁能帮忙解释一下为什么?我在下面包含了我的模型的简化版本。
InvalidOperationException:表达式“b.BrandId”无效 在“包含”操作中,因为它不代表属性 访问:'t => t.MyProperty'。定位在派生上声明的导航 类型,使用强制转换 ('t => ((Derived)t).MyProperty') 或 'as' 运算符 ('t => (t as Derived).MyProperty')。收藏导航 可以通过组合 Where、OrderBy(Descending)、 ThenBy(Descending)、Skip 或 Take 操作。
我有一个 Products 表和一个 Brands 表。品牌是独一无二的,产品只能有一个品牌,但一个品牌可以有多个产品。
产品模型和品牌模型:
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 中,这就是引发上述错误的原因。包含品牌部分是为了让我可以在我的索引页面上显示品牌名称,并且在那里可以追踪错误:
// GET: Products
public async Task<IActionResult> Index()
{
return View(await _context.Products.Include(b => b.Brand)
.OrderByDescending(d => d.CreatedDate)
.AsNoTracking().ToListAsync());
}
【问题讨论】:
-
您的原始代码中可能有错字。根据您将
b.BrandId放入.Include的错误消息,而不是b.Brand。 -
谢谢!您的评论足以让我再次查看并看到我的错误 - 请参阅我对标记为答案的回复的评论。
-
你应该从你的
Product构造函数中删除Brand初始化,否则Brand的属性将不会被设置。
标签: c# entity-framework .net-core entity-framework-core