How to update entity?

后端 未结 1 1876
谎友^
谎友^ 2021-01-28 02:43

I had a question more detailed earlier which I had no answer, I will have the same question with a simpler way:

I have an EF database with foreign key to another table.

相关标签:
1条回答
  • 2021-01-28 03:43

    Could you do something simple like detaching the entity, then attaching it to the context when you're ready to save?

    MemberManager currentMemberManager = new MemberManager();
    Member NewMember = currentMemberManager.GetById(2);
    

    The get:

    public Member GetById(int id)
    { 
      var member = YourContext.Members.FirstOrDefault(m => m.id == id);
      YourContext.Detach(member);
      return member;
    }
    

    The save:

    public void Save2(Member newMember)
            {
                using (var Context = new NoxonEntities())
                {
                    Context.Attach(newMember);
                    Context.ObjectStateManager.ChangeObjectState(newMember, EntityState.Modified);
                    Context.SaveChanges();
                }
            }
    
    0 讨论(0)
提交回复
热议问题