如何更新 EF ObjectContext 中通用实体的属性?
我想使用通用类在 ObjectContext 中创建通用更新方法。我需要循环所有属性并根据传递给通用更新方法的通用实体更新它们。 update 方法:
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:更新、插入和删除方法后,我的框架调用 myContext.SaveChanges()。
I would like to create a generic update method in a ObjectContext, using a generic class. I need to loop all properties and update them based in a generic entity that i pass to my generic update method. The update method:
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);
}
}
But this doesn't work because the properties are passed by value, Right? So, there is a way to modify the current entity properties?
OBS: After Update, Insert and Remove methods my framework calls myContext.SaveChanges().
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
假设您想要将
entity
的值设置为currentEntity
(否则,只需使用相反的方法)。Assuming you want to set values from
entity
tocurrentEntity
(otherwise, just use the reverse).要在拥有
PropertyInfo
对象时获取或设置值,您必须使用它们的SetValue
和GetValue
方法。To get or set value when you have
PropertyInfo
object you have to use theirSetValue
andGetValue
methods.