Update a record without first querying?

前端 未结 7 613
南方客
南方客 2020-11-28 04:29

Lets say I query the database and load a list of items. Then I open one of the items in a detail view form, and instead of re-querying the item out of the database, I create

7条回答
  •  青春惊慌失措
    2020-11-28 05:10

    If the DataItem has fields EF will pre-validate (like non-nullable fields), we'll have to disable that validation for this context:

    DataItem itemToUpdate = new DataItem { Id = id, Itemstatus = newStatus };
    dataEntity.Entry(itemToUpdate).Property(x => x.Itemstatus).IsModified = true;
    dataEntity.Configuration.ValidateOnSaveEnabled = false;
    dataEntity.SaveChanges();
    //dataEntity.Configuration.ValidateOnSaveEnabled = true;
    

    Otherwise we can try satisfy the pre-validation and still only update the single column:

    DataItem itemToUpdate = new DataItem
    {
        Id = id,
        Itemstatus = newStatus,
        NonNullableColumn = "this value is disregarded - the db original will remain"
    };
    dataEntity.Entry(itemToUpdate).Property(x => x.Itemstatus).IsModified = true;
    dataEntity.SaveChanges();
    

    Assuming dataEntity is a System.Data.Entity.DbContext

    You can verify the query generated by adding this to the DbContext:

    /*dataEntity.*/Database.Log = m => System.Diagnostics.Debug.Write(m);
    

提交回复
热议问题