![](/img/trans.png)
[英]EF 6, Update Entity from DTO, but only existing properties (generic code)
[英]How to update the properties of a generic entity in a EF ObjectContext?
我想使用一个通用类在ObjectContext中创建一个通用更新方法。 我需要循环所有属性,并根据传递给通用更新方法的通用实体对其进行更新。 更新方法:
public void Update(T entity)
{
if (entity == null)
{
throw new ArgumentNullException("entity");
}
var propertiesFromNewEntity = entity.GetType().GetProperties();
// I've a method that return a entity by Id, and all my entities inherits from
// a AbstractEntity that have a property Id.
var currentEntity = this.SelectById(entity.Id).FirstOrDefault();
if (currentEntity == null)
{
throw new ObjectNotFoundException("The entity was not found. Verify if the Id was passed properly.");
}
var propertiesFromCurrentEntity = currentEntity.GetType().GetProperties();
for (int i = 0; i < propertiesFromCurrentEntity.Length; i++)
{
propertiesFromCurrentEntity.SetValue(propertiesFromNewEntity.GetValue(i), i);
}
}
但这不起作用,因为属性是通过值传递的,对吧? 那么,有没有办法修改当前实体的属性呢?
OBS:更新后,我的框架会调用Insert和Remove方法myContext.SaveChanges()。
假设您要将entity
值设置为currentEntity
(否则,只需使用相反的方法即可)。
propertiesFromCurrentEntity[i].SetValue(
currentEntity, propertiesFromNewEntity[i].GetValue(entity, null), null);
要在拥有PropertyInfo
对象时获取或设置值,必须使用其SetValue
和GetValue
方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.