在实体框架中更新导航属性

时间:2019-09-04 08:52:50

标签: c# entity-framework entity-framework-6 lazy-loading

我是实体框架的新手 我只是想知道为什么Entity Framework不保存更改,尤其是导航属性,尽管所有其他属性都已更新 请我简单说明一下

这是我的服务类别

public  class ProductsService
{
    AppDbContext _Context;
    public ProductsService()
    {
        _Context = new AppDbContext();
    }

    public Product GetProduct(int id)
    {
        return _Context.Products.Include(p=>p.Category).Where(pro =>pro.Id == id).SingleOrDefault();
    }

    public void UpdateProduct(Product product)
    {
        _Context.Entry(product).State = System.Data.Entity.EntityState.Modified;
        _Context.SaveChanges();
    }
}

在控制器中:

[HttpPost]
public ActionResult Edit(NewCategoryViewModel pro,int Id)
{
    CategoriesService ser = new CategoriesService();
    var NewProduct = ProService.GetProduct(Id);
    var NewCat = ser.GetCategory(pro.CategoryId);
    NewProduct.Description = pro.Description;
    NewProduct.Name = pro.Name;
    NewProduct.Price = pro.Price;
    NewProduct.Category = NewCat;

    ProService.UpdateCategory(NewProduct);
    return RedirectToAction("ProductTable");
}

我已经尝试过了,效果很好

[HttpPost]
public ActionResult Edit(NewCategoryViewModel pro,int Id)
{

    using (var Context = new AppDbContext())
    {
        var NewProd = Context.Products.FirstOrDefault(pr => pr.Id == Id);
        var Cat = Context.Categories.FirstOrDefault(cat => cat.Id == pro.CategoryId);
        Context.Entry(NewProd).State = EntityState.Modified;
        NewProd.Name = pro.Name;
        NewProd.Description = pro.Description;
        NewProd.Price = pro.Price;
        NewProd.Category = Cat;
        Context.SaveChanges();
    }
}

以及UpdateCategory

public void UpdateCategory(Category category)
{
    using (var Context = new AppDbContext())
    {
        Context.Entry(category).State = System.Data.Entity.EntityState.Modified;
        Context.SaveChanges();
    }
} 

为什么第一个不起作用 我知道导航属性状态可能有问题

2 个答案:

答案 0 :(得分:0)

您可以考虑使用.add()而不是.entry()。 .add()还将跟踪其他可达实体。

文档可在此处找到: entity framework

答案 1 :(得分:0)

由于您在DbContext内创建了ProductService,并在其中创建了新的上下文:

public void UpdateCategory(Category category) 
{ 
    using (var Context = new AppDbContext()) 
    { 
        Context.Entry(category).State = System.Data.Entity.EntityState.Modified; 
        Context.SaveChanges(); 
    }
}

->您可以同时使用两个不同的DbContext(这可能会导致更改跟踪问题)!

解决方案: 尝试对所有DbContext使用DependencyInjection,而不是在本地创建它们,以防止更改跟踪出现问题。