atp9
atp9

Reputation: 890

How to achieve partial update in Entity Framework 5/6?

I am working on Entity framework with database first approach and I came across below issue.

I have a Customer table with columns col1, col2, col3 ,....,col8. I have created an entity for this table and this table has around 100 records already. Out of above 8 columns, col4 is marked as Non-null.

Class Customer
    {
         member col1;
         member col2;
         member col3;
         member col4;
         .
         .
         member col8;
    }
    class Main
    {
       //main logic to read data from database using EF 
       Customer obj = object of Customerwith values assigned to col1,col2 and col3 members
       obj.col2=some changed value.
       DBContext.SaveChanges(); //<- throws an error stating it is expecting value of col4. 

    }

In my application, I am trying to read the one of the record using the stored procedure using EF and stored procedure only returns col1,col2 and col3. I am trying to save the modified value of col2 and trying to save back to database using DBContext. But it thows an error stating value of required field col4 is not provided.

FYI: I have gone through couple of forums and question and option to go with disabled verfication on SaveChanges is not feasible for me.

Is there any other way through which I can achieve partial update?

Upvotes: 2

Views: 1347

Answers (2)

Gert Arnold
Gert Arnold

Reputation: 109109

disabled verfication on SaveChanges is not feasible for me

Sure it is. You even have to disable validation on Save. But then you can't mark the whole entity as modified, which I think you did. You must mark individual properties as modified:

var mySmallCustomer = someService.GetCustomer(); // from sproc
mySmallCustomer.col2 = "updated";

var myLargeCustomer = new Customer();
context.Customers.Attach(myLargeCustomer);
Entry(myLargeCustomer).CurrentValues.SetValues(mySmallCustomer);

// Here it comes:
Entry(myLargeCustomer).Property(c => c.col2).IsModified = true;

context.Configuration.ValidateOnSaveEnabled = false;
context.SaveChanges();

So you see it's enough to get the "small" customer. From this object you create a stub entity (myLargeCustomer) that is used for updating the one property.

Upvotes: 0

Ilya Chumakov
Ilya Chumakov

Reputation: 25019

I guess EntityFramework.Utilities satisfies your conditions.

This code:

using (var db = new YourDbContext())
{
    db.AttachAndModify(new BlogPost { ID = postId }).Set(x => x.Reads, 10);
    db.SaveChanges();
}

will generate single SQL command:

exec sp_executesql N'UPDATE [dbo].[BlogPosts]
SET [Reads] = @0
WHERE ([ID] = @1)
',N'@0 int,@1 int',@0=10,@1=1

Upvotes: 1

Related Questions