通用仓储与EF 5.0不起作用

3

我有一个通用仓库用于管理实体,所有的实体(由代码生成项生成)都有一个个性化的partial实现了IID接口,在这个阶段,所有的实体都必须拥有Int32类型的Id属性。

因此,我的问题是更新操作,以下是我的代码:

public class RepositorioPersistencia<T> where T : class
{
    public static bool Update(T entity)
    {
        try
        {
            using (var ctx = new FisioKinectEntities())
            {
                // here a get the Entity from the actual context 
                var currentEntity = ctx.Set<T>().Find(((BLL.Interfaces.IID)entity).Id);

                var propertiesFromNewEntity = entity.GetType().GetProperties();
                var propertiesFromCurrentEntity = currentEntity.GetType().GetProperties();

                for (int i = 0; i < propertiesFromCurrentEntity.Length; i++)
                {
                    //I'am trying to update my current entity with the values of the new entity
                    //but this code causes an exception
                    propertiesFromCurrentEntity[i].SetValue(currentEntity, propertiesFromNewEntity[i].GetValue(entity, null), null);
                }
                ctx.SaveChanges();
                return true;
            }

        }
        catch
        {

            return false;
        }
    }
 }

有人能帮我吗?这让我抓狂了。
1个回答

2
您可以使用EF API按以下方式更新实体的值。
public static bool Update(T entity)
{
    try
    {
        using (var ctx = new FisioKinectEntities())
        {
            var currentEntity = ctx.Set<T>().Find(((BLL.Interfaces.IID)entity).Id);

            var entry = ctx.Entry(currentEntity);
            entry.CurrentValues.SetValues(entity);

            ctx.SaveChanges();
            return true;
        }
    }
    catch
    {

        return false;
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接