【问题标题】:How to update the properties of a generic entity in a EF ObjectContext?如何更新 EF ObjectContext 中通用实体的属性?
【发布时间】:2012-01-24 17:17:21
【问题描述】:

我想使用泛型类在 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:在更新、插入和删除方法之后,我的框架调用 myContext.SaveChanges()。

【问题讨论】:

  • 你在属性数组上调用 SetValue...我不认为这是你打算做的 ;)

标签: c# entity-framework generics reflection


【解决方案1】:

假设您要将值从entity 设置为currentEntity(否则,只需使用相反的值)。

propertiesFromCurrentEntity[i].SetValue(
    currentEntity, propertiesFromNewEntity[i].GetValue(entity, null), null);

【讨论】:

    【解决方案2】:

    要在拥有PropertyInfo 对象时获取或设置值,您必须使用它们的SetValueGetValue 方法。

    【讨论】:

      猜你喜欢
      • 2014-12-03
      • 2011-02-12
      • 1970-01-01
      • 2021-11-06
      • 2023-04-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多