更新
如果使用存储库模式,你不能去进行多次的DbContext,您可以创建一个通用的,它传递给你的通用存储库象下面这样:
public class Repository<T> : IRepository<T>
where T : EntityBase
{
internal MyDbContext context;
internal DbSet<T> dbSet;
public Repository()
{
context = new MyDbContext();
this.dbSet = context.Set<T>();
}
public void Add(T entity)
{
dbSet.Add(entity);
}
public void Delete(T entity)
{
dbSet.Remove(entity);
}
public void Delete(int id)
{
dbSet.Remove(dbSet.Find(id));
}
public T GetById(int id)
{
return dbSet.Find(id);
}
public IEnumerable<T> GetAll()
{
return dbSet.AsEnumerable();
}
public void Update(T entity)
{
dbSet.Attach(entity);
context.Entry(entity).State = EntityState.Modified;
}
public void Save()
{
context.SaveChanges();
}
}
,你应该还包括您的DbSets。
如果你正在做的EF代码优先那么它你根据需要多少,但没有更多的设计您POCO
类。但根据你所说的800
表我想你可能想试试Database-First
方法。我非常仔细地建议你这个article,因为它可以解释你需要的一切。
更新:
如果你走近这个从数据库首先:Ado.NET Entity Model
创建你的DbContext为您服务!如果仔细观察.Edmx文件,它基本上就是您的POCO类。
现在,如果你尝试代码优先方法,可以说你有这样的DbContext类:
public class MyDbContext : DbContext
{
public MyDbContext()
: base("name=MyConnection")
{
Database.SetInitializer(new MigrateDatabaseToLatestVersion<MyDbContext, YourApplication.Migrations.Configuration>("MyConnection"));
}
//Every time you need to add new Table you add them here.
public DbSet<Users> Users { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
//And Map them here
modelBuilder.Configurations.Add(new UsersMap());
}
}
您只需添加一个新的DbSet<Class>
您DbContext
象下面这样:
public DbSet<POCO CLASS> CLASS { get; set; }
等等,我通常为我的MVC应用程序中的每个Area
创建一个DbContext
。所以你可以像Admin Area
- >AdminDbContext
等等。
只需使用DB第一种方式,并导入了所需的实体。 – Ric
你不想要800+表格对象的一个模型。你可以有多个dbcontext模型。你可以创建一个模型来处理工作人员,另一个模型可以处理课程,或者你的项目处理的其他任何领域 – JamieD77
已更新我的回答 – Valkyrie