mju*_*juk 9 c# entity-framework entity-framework-core .net-core
我在 Entity Framework Core MVC 应用程序上收到以下错误。任何人都可以帮忙解释为什么吗?我在下面提供了我的模型的简化版本。
InvalidOperationException:表达式“b.BrandId”在“Include”操作中无效,因为它不表示属性访问:“t => t.MyProperty”。要定位在派生类型上声明的导航,请使用强制转换 ('t => ((Derived)t).MyProperty') 或 'as' 运算符 ('t => (t as Derived).MyProperty')。可以通过组合Where、OrderBy(降序)、ThenBy(降序)、Skip 或 Take 操作来过滤集合导航访问。
我有一个产品表和一个品牌表。品牌是唯一的,产品只能有一个品牌,但一个品牌可以有很多产品。
产品型号及品牌型号:
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; }
}
Run Code Online (Sandbox Code Playgroud)
然后在我的 ProductsController 中,这就是引发上述错误的原因。包含品牌部分是为了我可以在我的索引页面上显示品牌名称,并且可以在那里追踪到错误:
// GET: Products
public async Task<IActionResult> Index()
{
return View(await _context.Products.Include(b => b.Brand)
.OrderByDescending(d => d.CreatedDate)
.AsNoTracking().ToListAsync());
}
Run Code Online (Sandbox Code Playgroud)
您的类未正确配置,并且未创建任何构造函数:
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; }
}
Run Code Online (Sandbox Code Playgroud)
我只是想分享我的解决方案,在 ICollection 上出现类似的错误
我的错误
// My error here was my collection, because it is a field
public ICollection<Product> Products = new List<Product>();
Run Code Online (Sandbox Code Playgroud)
解决方案
// I just had to make it as a Property
public ICollection<Product> Products { get; set; } = new List<Product>();
Run Code Online (Sandbox Code Playgroud)
我花了一段时间才发现我的小错误......但现在这个错误对我来说真的很明显
因为它不代表属性访问:'t => t.MyProperty'。
| 归档时间: |
|
| 查看次数: |
25504 次 |
| 最近记录: |