我打算将一个旧项目移至带有EF的ASP.NET MVC,并且存在一个问题。几个项目的DbContext。 ASP.NET MVC EF
我的项目包含几个子项目,每个项目都有自己的表格,尽管表格结构相同。
Ex。 XXX_Customers,YYY_Customers等
我发现了一个解决方案来实现我想要的。 (使用if-else-then语句)。
控制器动作:
public ActionResult Index(string projectname)
{
List<Customers> list = new List<Customers>() ;
if (projectname=="XXX")
{
list = new BaseContext().Customers.ToList();
}
else if (projectname=="YYY")
{
list = new BaseContext2().Customers.ToList();
}
return View(list);
}
型号:
public class Customers
{
public int Id { get; set; }
public string Name { get; set; }
public string UniqueValue { get; set; }
}
public class BaseContext : DbContext
{
public BaseContext()
: base("myconnectionstring")
{
Configuration.LazyLoadingEnabled = false;
}
public DbSet<Customers> Customers { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Customers>().Property(p => p.Id).HasColumnName("ID");
modelBuilder.Entity<Customers>().Property(p => p.Name).HasColumnName("Name");
modelBuilder.Entity<Customers>().Property(p => p.UniqueValue).HasColumnName("UniqueValue");
modelBuilder.Entity<Customers>().ToTable("XXX_Table1", "MyScheme");
}
}
public class BaseContext2 : DbContext
{
public BaseContext2()
: base("myconnectionstring")
{
Configuration.LazyLoadingEnabled = false;
}
public DbSet<Customers> Customers { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Customers>().Property(p => p.Id).HasColumnName("ID");
modelBuilder.Entity<Customers>().Property(p => p.Name).HasColumnName("Name");
modelBuilder.Entity<Customers>().Property(p => p.UniqueValue).HasColumnName("UniqueValue");
modelBuilder.Entity<Customers>().ToTable("YYY_Table1", "MyScheme");
}
}
那么,有没有这样做没有的if-else-then语句什么好办法?
也许通过在'class BaseContext:DbContext,IGenericContext'等所有上下文中定义和实现通用接口,或者使用'dynamic'关键字? –