Entity Framework 在我尝试更新父实体时正在更新子实体

Entity Framework is updating child entity when I try to update parent entity

我有一个映射到产品 table:

Product 实体
[Table("Product")]
public class Product
{
    public int Id { get; set; }
    public string Name { get; set; } 
    public decimal Price { get'; set; }
}

我还有一个映射到 CombinedProductView 的 CombinedProduct 实体,请注意,此实体仅供阅读,此视图 不是 updatable :

[Table("CombinedProductView")]
public class CombinedProduct : Product
{
    public string Store { get; set; } 
}

这是我的 MyDbContext:

[DbConfigurationType(typeof(MySqlEFConfiguration))]
public class MyDbContext: DbContext
{
    public MyDbContext() : base("MyDB")
    {
    }

    public DbSet<Product> Product { get; set; }
    public DbSet<CombinedProduct> CombinedProduct { get; set; }
}

我有一个存储库,它有一个方法 return List of Products 和另一个保存 Products 的方法:

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

我想将某些产品的价格提高 5 美元,所以我得到了 Product 的列表并提高了价格:

var products = _productRepository.GetProductsMoreExpensiveThan(100);
foreach(var p in products)
{
    p.Price += 5;
}

_productRepository.Update(products);

这会引发异常,因为 EF 正在尝试更新 CombinedProductView 而不是 updatable。为什么 Entity Framework 在更新基本实体 Product 时尝试更新派生实体 (CombinedProduct)?

我相信混淆来自 Product 的基础 class 有一个 [Table("Product")] 属性,然后派生的 class 也有一个。

您可以在 EF 的对象类型中使用基数 class,但是,基数 class 通常不代表 table。

这里有很多关于如何设法完成这项工作的方法需要展开,所以与其试图将其扩展到疯狂的细节,这篇关于 Inheritance Strategies with EF 的文章应该有助于清除它向上,因为它提供了 table 名称等基础知识的详细信息