[英]Best way to update a record using Entity Framework
我想使用实体框架在表中进行更新。 但是,我得到一个错误。
我的EfRepositoryBase
类正在实现IEntityRepository
。 这种方法有什么问题?
public bool UpdateWithProperty(TEntity entity, params Expression<Func<TEntity, object>>[] properties)
{
using (var context = new TContext())
{
context.Set<TEntity>().Attach(entity);
var updatedEntity = context.Entry(entity);
foreach (var property in properties)
{
updatedEntity.Property(property).IsModified = true;
}
updatedEntity.State = EntityState.Modified;
context.SaveChanges();
}
return true;
}
错误:
无法将值NULL插入表“ Nextt.dbo.Users”的“ UserName”列中; 列不允许为空。 更新失败。
您可以这样使用。
db.context.Attach(obj);
DbEntityEntry entry = db.Entry(obj);
foreach (var proprty in entry.OriginalValues.PropertyNames)
{
if(entry.CurrentValues.GetValue<object>(proprty) != null)
if (!object.Equals(entry.GetDatabaseValues().GetValue<object>(proprty), entry.CurrentValues.GetValue<object>(proprty)))
{
entry.Property(proprty).IsModified = true;
}
}
db.SaveChanges();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.