Reputation: 33
If there is a entity named UserInfo
, UserId
is the primary key, I defined entity as following
UserInfo userInfonew = new UserInfo()
{
UserId=userInfo.UserId,
Email = userInfo.Email,
FirstName = userInfo.FirstName,
LastName = userInfo.LastName,
LastUpdateBy = GetCurrentUserGuid(),
LastUpdate = DateTime.Now
};
If we want to update all entity fields, we have method as follows
db.Entry(userInfonew).State = EntityState.Modified;
db.SaveChanges();
If we want to update some fields, for example, we just want to update email field:
db.UserInfoes.Attach(userInfonew);
db.Entry(userInfonew).Property(x => x.Email).IsModified = true;
db.SaveChanges();
But if there are 20 fields in this entity, if we want to update 18 fields, the two fields left don't need update, we have to write 18 times about db.Entry(userInfonew).Property(x => x.field).IsModified = true
, is there any way about this? I don't want to write so many times about this.
Upvotes: 0
Views: 445
Reputation: 8676
If you do not get original data from source and if properties which you do not want to update are known, you can actually use Reflection to achieve what you want. What you have to do is create an extension method (can also be ordinary method if you prefer so) which changes state of properties as below:
public static void SetPropertiesToModeified<TEntity>(
this MyContext context,
TEntity entity,
List<string> propertiesNotToUpdate)
{
// Get properties to update. Get all properties and
// exclude the ones you do not want to update.
List<string> propertiesToUpdate = typeof(TEntity)
.GetProperties()
.Select(m => m.Name)
.Except(propertiesNotToUpdate) // exculde propeties not update
.ToList();
DbEntityEntry<TEntity> entry = context.Entry(entity);
propertiesToUpdate.ForEach(
p => entry.Property(p).IsModified = true);
}
Then, you can use it like:
using(MyDbContext context = new MyDbContext())
{
UserInfo userInfo = .....;
context.UserInfoes.Attach(userInfo);
List<string> propertiesNotToUpdate = new List<string>
{
"UserId",
"RegistrationDate"
};
context.SetPropertiesToModeified(userInfo, propertiesNotToUpdate);
context.SaveChanges();
}
Upvotes: 1