c# - 我有一个 POCO,我可以从 DbContext 获得代理吗?

标签 c# asp.net-mvc entity-framework

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

我能否根据模型的 POCO 获得具有所有覆盖功能的代理

(我假设这就是 db.Entry().Entity 的用途,但它仍然返回 POCO 对象,而不是代理。我正在检查在断点暂停期间将鼠标悬停在对象上。)

最佳答案

此代码中的某些内容将满足您的需要。我用过 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;
    }
}

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

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;
    }
}

关于c# - 我有一个 POCO,我可以从 DbContext 获得代理吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17168675/

相关文章:

c# - Entity Framework 未填充键

c# - 如何验证该列是否存在于 DataRow 对象中?

c# - 多对多和一对多 (EF) - Code First

c# - 在 ASP.NET MVC 3 中使用 ASP.NET Membership e Profile

c# - 使用 LINQ 更新记录

c# - 使用 Entity Framework 实现 MVVM 模式 - 添加删除

c# - SQLException : Invalid object name c#

c# - 如何将 IHttpContextAccessor 注入(inject) Autofac TenantIdentificationStrategy

c# - MVC5 根据另一个文本框值动态禁用文本框

c# - 将类从 MVC 传递到 Web API