且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我有一个POCO,我可以从一个的DbContext代理?

更新时间:2023-01-19 18:37:48

沿着这code的东西线会做你的需要。我用 automapper ,向在实体传递给代理的版本复制值。

Something along the lines of this code will do what you need. I've used automapper to copy values from the passed in entity to the proxied version.

在code检查是否在实体传递是一个代理与否,并相应地处理它。

The code checks whether the passed in entity is a proxy or not and handles it accordingly.

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


更新:由@Colin在评论中所述,这并不需要版本 automapper


UPDATE version as described by @Colin in the comments that does not need 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;
    }
}