[英]Entity Framework is updating child entity when I try to update parent entity
I have a Product
entity which is mapped to Product table:我有一个映射到产品表的
Product
实体:
[Table("Product")]
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get'; set; }
}
I also have a CombinedProduct
entity which is mapped to CombinedProductView, note that this entity is only for reading, this view is not updatable :我还有一个映射到 CombinedProductView 的
CombinedProduct
实体,注意这个实体仅供阅读,这个视图是不可更新的:
[Table("CombinedProductView")]
public class CombinedProduct : Product
{
public string Store { get; set; }
}
And this is my MyDbContext
:这是我的
MyDbContext
:
[DbConfigurationType(typeof(MySqlEFConfiguration))]
public class MyDbContext: DbContext
{
public MyDbContext() : base("MyDB")
{
}
public DbSet<Product> Product { get; set; }
public DbSet<CombinedProduct> CombinedProduct { get; set; }
}
I have a repository which has a method to return a List
of Product
s and another method for saving Product
s:我有一个存储库,它有一个返回
Product
List
的方法和另一种保存Product
的方法:
Public class ProductRepository
{
public List<Product> GetProductsMoreExpensiveThan(decimal price)
{
return _context.Product.AsNoTracking().Where(p => p.Price > price).ToList();
}
public void Update(List<Product> products)
{
foreach (var p in products)
{
_context.Product.Attach(p);
_context.Entry(p).State = EntityState.Modified;
}
_context.SaveChanges();
}
}
I want increase the price of some products by $5, so I get a list of Product
s and increase the price:我想将某些产品的价格提高 5 美元,所以我得到一个
Product
列表并提高价格:
var products = _productRepository.GetProductsMoreExpensiveThan(100);
foreach(var p in products)
{
p.Price += 5;
}
_productRepository.Update(products);
This throws exception, because EF is trying to update CombinedProductView
which is not updatable.这会引发异常,因为 EF 正在尝试更新不可更新的
CombinedProductView
。 Why is Entity Framework is trying to update the derived entity ( CombinedProduct
) when updating the base entity Product
?为什么实体框架在更新基础实体
Product
时尝试更新派生实体( CombinedProduct
产品)?
I believe the confusion is coming from your base class of Product
having a [Table("Product")]
attribute on it, and then the derived class additionally having one.我相信混乱来自您的基础 class
Product
有一个[Table("Product")]
属性,然后派生的 class 也有一个。
You can use a base-class within object types in EF, however, that base class is typically NOT representing a table.您可以在 EF 中的 object 类型中使用基类,但是,基本 class 通常不代表表。
There is a lot to unwrap here as to methods of how you can manage to make this work, so rather than try to expand this into a crazy level of detail this article on Inheritance Strategies with EF should help clear it up as it provides detail on the basics for table names etc.这里有很多关于如何设法完成这项工作的方法,所以不要试图将其扩展到疯狂的详细程度,这篇关于Inheritance 策略的文章应该有助于清除它,因为它提供了关于表名等基础知识
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.