簡體   English   中英

更新通用存儲庫中的實體時出錯

[英]Error Updating Entity in a Generic Repository

我正在構建一個通用存儲庫,除了更新之外,所有其他方法都可以工作。 這是代碼:

 public void Update(T1 obj)
    {
        T2 item = Mapper.Map<T1, T2>(obj);
        //db.Entry(item).State = EntityState.Modified;
        //db.Set<T2>().Attach(item);
        db.Entry<T2>(item).State = EntityState.Modified;
        db.SaveChanges();

    }

我正在使用AutoMapper將我的業務模型映射到我的實體模型。 在我的控制器中,我有以下內容:

        userModel = userIDService.SelectByID(id);
        userModel.Active = false;
        userIDService.Update(userModel);

該模型運行良好,並將Active值作為False。 但它給了我以下錯誤:

Attaching an entity of type 'Data.UserIdentification' failed because 
another entity of the same type already has the same primary key value. 
 This can happen when using the 'Attach' method or setting the state of 
 an entity to 'Unchanged' or 'Modified' if any entities in the graph 
have conflicting key values. This may be because some entities are new 
and have not yet received database-generated key values. In this case 
 use the 'Add' method or the 'Added' entity state to track the graph and 
 then set the state of non-new entities to 'Unchanged' or 'Modified' as 
appropriate.

我怎樣才能解決這個問題? 我嘗試過幾種方法都沒有成功。 添加了通用回購代碼:

public class GenericRepository<T1, T2>:IGenericRepository<T1> 
    where T1 : class
    where T2: class

{
    private Data.Entities db = null;
    private DbSet<T2> table = null;

    public GenericRepository()
    {
        this.db = new Data.Entities();
        table = db.Set<T2>();
    }

    public GenericRepository(Entities db)
    {
        this.db = db;
        table = db.Set<T2>();
    }

    public IQueryable<T1> SelectAll()
    {
        return table.ToList().AsQueryable().Select(x => Mapper.Map<T2, T1>(x));
    }

    public T1 SelectByID(object id)
    {
        return Mapper.Map<T2, T1>(table.Find(id));
    }

    public void Insert(T1 obj)
    {
        T2 item = Mapper.Map<T1, T2>(obj);
        table.Add(item);
    }

    public void Update(T1 obj)
    {
        //T2 item = Mapper.Map<T1, T2>(obj);
        //table.Attach(item);
        //db.Entry<T2>(item).State = EntityState.Modified;
        //db.SaveChanges();
        T2 item = Mapper.Map<T1, T2>(obj);
        db.Set<T2>().Attach(item);
        db.Entry<T2>(item).State = EntityState.Modified;
        db.SaveChanges();




    }

    public void Delete(object id)
    {
        T2 existing = table.Find(id);
        table.Remove(existing);
    }

    public void Save()
    {
        db.SaveChanges();
    }

EDIT2:添加了UserIdentification實體

 public partial class UserIdentification
{
    public System.Guid id { get; set; }
    public System.Guid user_id { get; set; }
    public int id_type { get; set; }
    public System.DateTime expiration_date { get; set; }
    public System.DateTime Created { get; set; }
    public Nullable<bool> Active { get; set; }

    public virtual IdentificationType IdentificationType { get; set; }
    public virtual UserInfo UserInfo { get; set; }
}

編輯3:商業模式

    public Guid id { get; set; }
    public System.Guid user_id { get; set; }
    public int id_type { get; set; }
    public System.DateTime expiration_date { get; set; }
    public System.DateTime Created { get; set; }
    public Nullable<bool> Active { get; set; }
    public virtual IdentificationType IdentificationType { get; set; }

如果對檢索和更新操作使用相同的DbContext ,則在更新時,上下文已跟蹤您的實體(具有此主鍵的實體)。 來自MSDN

更改被跟蹤實體的狀態

您可以通過在其條目上設置State屬性來更改已被跟蹤的實體的狀態。 例如:

var existingBlog = new Blog { BlogId = 1, Name = "ADO.NET Blog" }; 

using (var context = new BloggingContext()) 
{ 
    context.Blogs.Attach(existingBlog); 
    context.Entry(existingBlog).State = EntityState.Unchanged; 

    // Do some more work...  

    context.SaveChanges(); 
}

請注意,為已跟蹤的實體調用“添加”或“附加”也可用於更改實體狀態。 例如,為當前處於已添加狀態的實體調用Attach將將其狀態更改為Unchanged。

我認為你錯過了Attach調用(你注釋掉了)。 請試試

public void Update(T1 obj)
{
    T2 item = Mapper.Map<T1, T2>(obj);
    db.Set<T2>().Attach(item);
    db.Entry<T2>(item).State = EntityState.Modified;
    db.SaveChanges();
}

我只想把它留在這里:

https://vimeo.com/131633177

我有完全相同的問題,所有其他方法(添加,刪除,獲取)工作正常,更新的例外。 我在dbContext嘗試附加實體時收到錯誤:

    public virtual void Update(T entity)
    {
        dbSet.Attach(entity);
        dataContext.Entry(entity).State = EntityState.Modified;
    }

此存儲庫方法“studentRepository.Update(student);” 從服務層調用。

    public StudentAdapterModel SaveStudent(StudentAdapterModel studentAdapterModel)
    {
        try
        {
            Student student = null;
            if (studentAdapterModel.EventId == 0)
            {
                student = new Student();
                student = Mapper.Map<StudentAdapterModel, Student>(studentAdapterModel);
                studentRepository.Add(student);
            }
            else
            {
                //student = studentRepository.GetById(studentAdapterModel.EventId);
                student = studentRepository.Get(e => e.EventId == studentAdapterModel.EventId);
                try
                {
                    student = Mapper.Map<StudentAdapterModel, Student>(studentAdapterModel);

                }
                catch (Exception ex2)
                {
                    string errMess = ex2.ToString().Trim();
                }

                auctionEventRepository.Update(auctionEvent);

            }
            unitOfWork.Commit();
            studentAdapterModel.EventId = student.EventId;
            return studentAdapterModel;
        }
        catch (Exception ex)
        {
            string errMess = ex.ToString().Trim();
        }
        return null;
    }

但如果我不使用Mapper,它工作正常

    //student = studentRepository.GetById(studentAdapterModel.EventId);
            student = studentRepository.Get(e => e.EventId == studentAdapterModel.EventId);
            try
            {
                //student = Mapper.Map<StudentAdapterModel, Student>(studentAdapterModel);
                student.Name = StudentAdapterModel.Name;
            }
            catch (Exception ex2)
            {
                string errMess = ex2.ToString().Trim();
            }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM