Context Per Request: How to update Entity

前端 未结 1 784
难免孤独
难免孤独 2021-01-07 11:49

I have a repository class as shown below. There is a method to get entity object – GetPaymentByID. I am retrieving a Payment object and making a change to its PaymentType pr

相关标签:
1条回答
  • 2021-01-07 12:02

    You need to add (if the data is new) or attach (if the data is edited) the object to the context:

    http://blogs.msdn.com/b/adonet/archive/2011/01/29/using-dbcontext-in-ef-feature-ctp5-part-4-add-attach-and-entity-states.aspx

    Something along these lines:

    public void SaveContextChanges(MyEntityDataModelEDM.Payment paymentEntity)
    {
        using (var myObjectContext = new MyEntityDataModelEDM.LibraryReservationSystemEntities(connectionStringVal))
        {
            // use your own logic for determining a "new" entity
            myObjectContext.Entry(paymentEntity).State = 
                    (paymentEntity.PaymentID == default(int)) ?  
                                   EntityState.Added :
                                   EntityState.Modified;
    
            myObjectContext.SaveChanges();
        }
    }
    
    0 讨论(0)
提交回复
热议问题