2017-08-01 5 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

単純にジェネリックを使用できます。これを非常に簡単に行う方法は複数あります。ここでは一つの方法です:http://www.tugberkugurlu.com/archive/generic-repository-pattern-entity-framework-asp-net-mvc-and-unit-testing-triangle

:考慮事項のようなもので...

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 
} 

しかし、私は、これは良いアイデアではないと思い、あなたがリポジトリをご覧ください

関連する問題