2016-12-02 8 views
0

私はいくつかのクラスを持っています:User.cs,など...すべてがすべての主なロジックがあるBaseCore.csの子です。ここでクラス別のエンティティコレクション

は私dbContextクラス(簡体字)である:

public class MyContext : DbContext { 
    public MyContext() : base("AppEntityDB") { 
     System.Data.Entity.Database.SetInitializer(new DropCreateDatabaseAlways<MyContext>()); 
    } 

    public virtual DbSet<User> Users { get; set; } 
    public virtual DbSet<Permissions> Permissions { get; set; } 
} 

は今、私はすべてのListFormsの親になりますbaseListForm.csを作成しています(Windowsはaplicationを形成する)

私はbaseListFormのようなすべての基本的な機能を持つようにしたいですSaveData();EditData()およびLoadData();ここで

は私のBaseListFormクラス(簡体字)である:

public partial class BaseListForm : Form { 
    private BaseCore _classType; 
    public virtual void LoadList() { 
     //I want here to load the collection of Mycontext() depending 
     // on what which class it calls. eg. if User.cs calls then i want 
     // to call DbSet<User> Users collection (accessible - _classType.Users) 
     var LoadCurrentClass = ClassType. 
    } 
} 

だから私は何とかthis.GetType();クラスのMyContext()から対応するコレクションを選択します。

答えて

0

1つのフォームが1つのデータセットにしかアクセスできないという場合は、ジェネリックを使用できます。

私の例以外の機能を追加できます。通常、データベース上のCRUD操作用のリポジトリまたは作業単位クラスを作成しますが、フォームが1 DbSetにアクセスするよう制限されます。私はあなたがそのアイデアを得ることを望みます。

フォームベース

public abstract class FormBase<T> : Form 
    where T : BaseCore 
{ 
    private ApplicationDbContext _db = new ApplicationDbContext(); 

    /// <summary> 
    /// Accessor for the DbSet 
    /// </summary> 
    protected DbSet<T> DbSet 
    { 
     get { return _db.Set<T>(); } 
    } 

    /// <summary> 
    /// Inform the DbContext of the changes made on an entity 
    /// </summary> 
    /// <param name="entity"></param> 
    protected void UpdateEntry(T entity) 
    { 
     _db.Entry(entity).State = EntityState.Modified; 
    } 

    /// <summary> 
    /// Save changes on the DbContext 
    /// </summary> 
    protected void SaveData() 
    { 
     _db.SaveChanges(); 
    } 
} 

ユーザーフォーム

public partial class frmUser : FormBase<User> 
{ 
    public frmUser() 
    { 
     InitializeComponent(); 
     User user = this.DbSet.FirstOrDefault(); // Get first user record 
     user.Name = "New Name"; // Set new name value 
     this.UpdateEntry(user); // Inform DbContext that user has changed 
     this.SaveData(); // Save the changes made to the DbContext 
    } 
} 
関連する問題