概括dbcontext AddOrUpdate

时间:2017-08-01 08:04:43

标签: entity-framework generics

我的代码:

public  class BaseController
{

    public  object AddUpdate(object obj)
    {
        using (var db = new StoreModel())
        {

            string nameObj = obj.ToString().Substring(obj.ToString().LastIndexOf(".") + 1);
            var property = db.GetType().GetProperty(nameObj);
            ((DbSet<CrmTicket>)property.GetValue(db)).AddOrUpdate((CrmTicket)obj);
            db.SaveChanges();
            return obj;

        }
    }

}

我想概括AddOrUpdate。 此代码有效但不通用,您可以看到 CrmTicket 。 我不能在他的位置加上 Type

((DbSet<obj.GetType()>)property.GetValue(db)).AddOrUpdate((obj.GetType())obj);
你可以帮帮我吗? 谢谢。

1 个答案:

答案 0 :(得分:0)

你可以简单地使用泛型。有很多方法可以很容易地做到这一点。这是一种方式:

public class BaseController 
{
    protected T AddOrUpdate<T>(T obj) where T : BaseEntity
    {
        if (obj == null) throw new ArgumentNullException(nameof(obj));

        using (StoreModel context = new StoreModel())
        {
            T entity = context.Set<T>().Find(obj.Id);

            // the entity doesn't exists yet, so we add it
            if (entity == null) 
            {
                context.Set<T>().Add(entity);
            }
            // the entity exists, so we must update it
            else
            {
                // do you update logic, like : entity.MyString = obj.MyString
                // ...

                // Note : there is no need to attach the entity because the Find method has already done it.
            }

            // Everything is done.
            context.SaveChanges();
        }

        return obj;
    }   
}

// This is your base class for all entity.
// If you want to use generics and have an AddOrUpdate method, 
// you must have something to rely on where you want to check if the object you want to insert is already in Db.
public class BaseEntity 
{
    public int Id { get; set; } // you should configure this as an Primary Key with Identity
}

但我认为这不是一个好主意......考虑到这些因素,您应该查看存储库:http://www.tugberkugurlu.com/archive/generic-repository-pattern-entity-framework-asp-net-mvc-and-unit-testing-triangle