entity-framework-4.1 - context.SaveChanges() 不更新 SqlServer 数据库中的数据

标签 entity-framework-4.1

当我调用 context.SaveChanges() 来更新特定产品时,更新未在数据库中注册。我也没有收到任何运行时错误。我注意到的是我的产品目录没有更新。我仍然看到相同的值(value)观。当我运行调试器时,我注意到数据库的连接状态已关闭。

这是实现 context.SaveChanges() 的类

namespace SportsStore.Domain.Concrete
{
   public class EFProductRepository : IProductRepository
   {
       private EFDbContext context = new EFDbContext();

       public IQueryable<Product> Products
       {
           get { return context.Products; }
       }

       public void SaveProduct(Product product)
       {
           if (product.ProductID == 0)
           {
               context.Products.Add(product);
           }

           context.SaveChanges();
       }
   }
 }

namespace SportsStore.Domain.Concrete
{
   public  class EFDbContext : DbContext
   {
     public DbSet<Product> Products { get; set; }
   }
}

namespace SportsStore.Domain.Entities
{
    public class Product
    {

      [HiddenInput(DisplayValue=false)]
      public int ProductID { get; set; }

      public string Name { get; set; }

      [DataType(DataType.MultilineText)]
      public string Description { get; set; }

      public string Category { get; set; }

      public decimal Price { get; set; }
    }
}

最佳答案

EFProductRepository 类中,在 SaveProduct 方法中调用 context.SaveChanges() 方法之前,您可以使用以下方法之一:以下方法可以持久保存对数据库的更改。

public void SaveProduct(Product product)
{
    if (product.ProductID == 0)
    {
       context.Products.Add(product);
    }
    //One approach to persist changes to database
    //var productInDB = context.Products.Single(x => x.ProductID ==product.ProductID);
    //context.Entry(productInDB).CurrentValues.SetValues(product);
    //context.SaveChanges();

    //Alternate Approach
    if (product.ProductID != 0)
    {
       context.Entry(product).State = System.Data.EntityState.Modified;
    }
    context.SaveChanges();
}

关于entity-framework-4.1 - context.SaveChanges() 不更新 SqlServer 数据库中的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12113193/

相关文章:

c# - 如何配置T4模板在不同项目中生成类

entity-framework-4.1 - Entity Framework 4.1 虚拟属性

c# - 从一个对象到同一实体类型的两个对象的多个关联

sql-server - EF4.1 : Possible to have zero-or-one to zero-or-one (0. .1 到 0..1) 关系?

entity-framework - DBContext 添加/附加事件?

entity-framework - 代码优先与模型/数据库优先

c# - 外键指向复合键

entity-framework - 有没有办法在不处理和重新实例化 DbContext 的情况下重置它?

entity-framework-4 - 如何定义 DatabaseGenerated.Computed 应该计算什么?

sql-server - Entity Framework 4 Code First 与树