VansFannel
VansFannel

Reputation: 45921

DbEntityValidationException: Do I have to send all required fields to update only one?

I'm developing a WCF Rest service with C# and Entity Framework Code First.

I have a table User with 10 columns, but this is a JSON representation for the required columns:

{
    "Name": "user_1",
    "Active": true,
    "Gender": 1,
    "Email": "[email protected]",
    "Birthday": "02/07/1971",
    "City": "city_1",
    "Country": "country_1"
}

This is how I update a User using Entity Framework Code First:

private User InsertOrUpdateUser(User user)
{
    try
    {
        using (var context = new MyContext())
        {
            context.Entry(user).State = user.UserId == 0 ?
                                            EntityState.Added :
                                            EntityState.Modified;
                context.SaveChanges();
        }
    }
    catch (Exception ex)
    {
        ctx.StatusCode = System.Net.HttpStatusCode.InternalServerError;
        ctx.SuppressEntityBody = true;
    }

    return user;
}

When I sent this user:

{
    "Name": "user_1-mod",
    "UserId": 1
}

I get the following error:

[System.Data.Entity.Validation.DbEntityValidationException] =
{"Validation failed for one or more entities. See 'EntityValidationErrors' property for more details."}

Do I have to send all required fields to update only one?

Upvotes: 1

Views: 777

Answers (1)

Johan
Johan

Reputation: 8266

No,

You do not need to send in all fields. You can use this code (with adjustments of course)

In my generic repository, I do this

DbSet dbSet = Context.Set<TEntity>();
dbSet.Attach(entity);
Context.Entry<TEntity>(entity).Property(e => e.YourPropertyName).IsModified = true;
Context.SaveChanges()

This says that only that property is modified and won't try update the rest. If the number of columns change with every request, you will need to write some logic to cater for that.

The magic lies in this line

 Context.Entry<TEntity>(entity).Property(e => e.YourPropertyName).IsModified = true;

Which can also be used like

Context.Entry<TEntity>(entity).Property("YourPropertyName").IsModified = true;

Upvotes: 1

Related Questions