![](/img/trans.png)
[英]Working with several instances of DbContext concurrently in EF6 and ASP.NET
[英]Several DbContext for several projects. ASP.NET MVC EF
我将使用EF将一个旧项目移至ASP.NET MVC,这是一个问题。
我的项目包括几个子项目,每个项目都有自己的表,尽管表结构相同。
防爆。 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语句,有没有什么好的方法呢?
您需要的是实现Factory Design Pattern 。
IDBCustomers
。 DbContext
类实现它。 在网上阅读有关工厂设计模式及其对您的好处的更多信息。
祝你好运。
public interface IDbCustomer
{
DbContext GetDbCustomer();
}
public class FactoryDbCustomer
{
static public IDbCustomer GetDbContext(string projectName)
{
IDbCustomer obCustomer = null;
switch (projectName)
{
case "XXX":
obCustomer = new context1();
break;
case "YYY":
obCustomer = new context2();
break;
default:
break;
}
return obCustomer;
}
}
public class context1 : IDbCustomer
{
public DbContext GetDbCustomer()
{
return new BaseContext();
}
}
public class context2 : IDbCustomer
{
public DbContext GetDbCustomer()
{
return new BaseContext2();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.