2016-12-02 46 views
0

我有几个类:User.cs,Permission.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; } 
} 

现在我创建baseListForm.cs,这将是所有ListForms的父(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. 
    } 
} 

所以我想以某种方式选择MyContext()相应的集合this.GetType();类。

回答

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