سؤال

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?

هل كانت مفيدة؟

المحلول

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");

Just for reference to my original question, if found the answer here:

Update a single property of a record in Entity Framework Code First

It also contains how to disable validation temporarily - very useful especially if you used EF Power Tools to reverse engineer your DB to code first classes.

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

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."

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top