开发者

Entity Framework Code First Update by Stub Entity

Is it possible in EF Code-First to update without querying the entire row in db by using stub objects,...

e.g.

public class Dinner 
{     
    public int DinnerID { get; set; }     
    public string Title { get; set; }     
    public DateTime EventDate { get; set; }     
    public string Address { get; set; }     
    public string Country { get; set; }     
    public string HostedBy { get; set; }       
}



Dinner dinner = dinner.DinnerID = 1;     
dinner.HostedBy = "NameChanged" 
nerdDinners.SaveChanges();

will the code above cre开发者_如何转开发ate an Update Statement which will make the following columns null for the row of DinnerID 1 ?

Title, EventDate, Address, Country

Is there a way or method like "PropertyModified" = true, then the rest make them = false, so that HostedBy is the only one that will be updated?


I think you are looking for ApplyCurrentValues

public void UpdateDinner(Dinner existingDinner)
{
    var stub = new Dinner { DinnerId = existingDinner.DinnerId };
    ctx.Dinners.Attach(stub);
    ctx.ApplyCurrentValues(existingDinner);
    ctx.SaveChanges();
}

ApplyCurrentValues copies the scalar values from the existing object to the object in the graph (in the above case - the stub entity).

From the Remarks section on MSDN:

Any values that differ from the original values of the object are marked as modified.

Is that what your after?


To build on Paul's answer, the following will work when you are using EF Model or Database First:

context.ObjectStateManager.GetObjectStateEntry(dinner).SetModifiedProperty("HostedBy");


I think you are looking for the Attach() method.

  • Attaching and Detaching Objects


Try this maybe, it is specific to EF Code First which seems to do it differently than just EF.

var dinner = context.Dinners.Find(1);

context.Entry(dinner).Property(d => d.HostedBy).IsModified = true;

context.SaveChanges();

From ADO.NET team blog

"Marking a property as modified forces an update to be send to the database for the property when SaveChanges is called even if the current value of the property is the same as its original value."

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜