我有一个POCO,我可以从DbContext获取代理吗?

The*_*kis 9 c# asp.net-mvc entity-framework

我有一个从POST请求获得的模型.由于我的视图定义了它的POCO类型,因此从提交的数据创建的对象也是POCO.作为POCO,它没有覆盖各种虚拟属性.因此,这些虚拟属性返回null.反过来,这意味着我必须根据外键进行单独的查询以浏览其属性(如果我想做更复杂的事情而不仅仅是保存它).

鉴于我的模型的POCO,我可以获得具有所有被覆盖功能的代理吗?

(我假设这是db.Entry().Entity为了什么,但它仍然返回POCO对象,而不是代理.我在断点暂停期间通过鼠标悬停检查对象的运行时类型.)

quj*_*jck 7

这段代码的某些内容将满足您的需求.我已经使用了automapper将值从传入的实体复制到代理版本.

代码检查传入的实体是否是代理,并相应地处理它.

public class Repository<T> where T : class
{
    private readonly Context context;
    private bool mapCreated = false;
    public Repository(Context context)
    {
        this.context = context;
    }

    protected virtual T InsertOrUpdate(T e, int id)
    {
        T instance = context.Set<T>().Create();
        if (e.GetType().Equals(instance.GetType()))
            instance = e;
        else
        {
            if (!mapCreated)
            {
                Mapper.CreateMap(e.GetType(), instance.GetType());
                mapCreated = true;
            }
            instance = Mapper.Map(e, instance);
        }

        if (id == default(int))
            context.Set<T>().Add(instance);
        else
            context.Entry<T>(instance).State = EntityState.Modified;

        return instance;
    }
}
Run Code Online (Sandbox Code Playgroud)

@Colin在不需要automapper的评论中描述的UPDATE版本

public class Repository<T> where T : class
{
    private readonly Context context;
    public Repository(Context context)
    {
        this.context = context;
    }

    protected virtual T InsertOrUpdate(T e, int id)
    {
        T instance = context.Set<T>().Create();
        if (e.GetType().Equals(instance.GetType()))
        {
            instance = e;
        }
        else
        {
            DbEntityEntry<T> entry = context.Entry(instance);
            entry.CurrentValues.SetValues(e);
        }

        context.Entry<T>(instance).State =
            id == default(int)
                ? EntityState.Added
                : EntityState.Modified;

        return instance;
    }
}
Run Code Online (Sandbox Code Playgroud)

  • Context.Entry.CurrentValues对象具有SetValues方法,该方法允许您设置属性而无需使用automapper.请参阅此解决方案 - http://stackoverflow.com/a/16811976/150342 (3认同)