Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 create 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?

like image 852
Henry Cortez Wu Avatar asked Dec 14 '10 15:12

Henry Cortez Wu


2 Answers

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?

like image 159
RPM1984 Avatar answered Oct 17 '22 04:10

RPM1984


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");
like image 36
Jonathan Freeland Avatar answered Oct 17 '22 05:10

Jonathan Freeland