相关疑难解决方法(0)

ObjectStateManager中已存在具有相同键的对象.ObjectStateManager无法使用相同的键跟踪多个对象

我有以下代码来添加或更新Entity对象.根据我添加或更新对象的响应,通过主键查找对象.

添加记录工作,但在更新期间它给出此错误消息" ObjectStateManager中已存在具有相同键的对象.ObjectStateManager无法跟踪具有相同键的多个对象"

在我的MSSQL数据库中,我只有一条记录.

var v = db.Envelopes.Find(model.ReportDate, model.Service);
if (v == null)
{
    db.Envelopes.Add(model);
    db.SaveChanges();
    ViewBag.status = "Record Add successfully";
    ModelState.Clear();
}
else
{
    db.Entry(model).State = EntityState.Modified;
    db.SaveChanges();
}
Run Code Online (Sandbox Code Playgroud)

我该如何修复此错误消息?

entity-framework asp.net-mvc-3

52
推荐指数
4
解决办法
6万
查看次数

"ObjectStateManager中已存在具有相同键的对象..."将实体状态设置为已修改时,将引发异常

我按照一些例子(包括诸如"Pro ASP.NET MVC 3"和"Professional ASP.NET MVC 3"之类的书籍)来使用EF 4.1创建简单的ASP.NET MVC 3应用程序(因为我是这些技术的新手).

我正在使用以下存储库(控制器的所有操作方法使用它的单个实例)来访问数据库:

public class ProductRepository : IProductRepository
    {
        private readonly EFDbContext _context = new EFDbContext();

        #region Implementation of IProductRepository       

       ....

        public void SaveProduct(Product product)
         {           
            if (product.ProductId == 0)
            {
                _context.Products.Add(product);
            }
            else
            {
                _context.Entry(product).State = EntityState.Modified;

            }

            _context.SaveChanges();
        }

....
}
Run Code Online (Sandbox Code Playgroud)

此存储库执行更新,如我使用的示例中所示.

产品类别:

public class Product
    {       
        public int ProductId { get; set; }       
        public string Name { get; set; }      
        public string Description { get; set; }     
        public decimal …
Run Code Online (Sandbox Code Playgroud)

entity-framework-4 asp.net-mvc-3

12
推荐指数
1
解决办法
2万
查看次数