Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/entity-framework/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何在EF ObjectContext中更新泛型实体的属性?_C#_Entity Framework_Generics_Reflection - Fatal编程技术网

C# 如何在EF ObjectContext中更新泛型实体的属性?

C# 如何在EF ObjectContext中更新泛型实体的属性?,c#,entity-framework,generics,reflection,C#,Entity Framework,Generics,Reflection,我想使用泛型类在ObjectContext中创建泛型更新方法。我需要循环所有属性,并根据传递给泛型更新方法的泛型实体更新它们。更新方法: public void Update(T entity) { if (entity == null) { throw new ArgumentNullException("entity"); } var propertiesFromNewEntity = entity.GetType().GetProperti

我想使用泛型类在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);
    }
}
公共作废更新(T实体)
{
if(实体==null)
{
抛出新的ArgumentNullException(“实体”);
}
var propertiesFromNewEntity=entity.GetType().GetProperties();
//我有一个按Id返回实体的方法,我的所有实体都继承自
//具有属性Id的抽象实体。
var currentEntity=this.SelectById(entity.Id).FirstOrDefault();
if(currentEntity==null)
{
抛出new ObjectNotFoundException(“未找到实体。请验证Id是否正确传递”);
}
var propertiesFromCurrentEntity=currentEntity.GetType().GetProperties();
对于(int i=0;i
但这不起作用,因为属性是按值传递的,对吗?那么,有没有一种方法可以修改当前的实体属性


OBS:更新后,插入并删除my framework调用myContext.SaveChanges()的方法。

假设要将值从
实体设置为
当前实体(否则,只需使用相反的方法)


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

您正在对属性数组调用SetValue。。。我不认为这是你打算做的;)
propertiesFromCurrentEntity[i].SetValue(
    currentEntity, propertiesFromNewEntity[i].GetValue(entity, null), null);