2017-08-01 56 views
0

我的代碼:概括的DbContext AddOrUpdate

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。 我不能把類型在他的地方。

((DbSet<obj.GetType()>)property.GetValue(db)).AddOrUpdate((obj.GetType())obj); 

你能幫我嗎? 謝謝。

回答

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