我的应用中有{4}层UI
,DomainClass
,Model(DBCntext)
,Repository
。
在存储库中,我有一个这样的抽象类:
public abstract class GenericRepository<C, T> :
IGenericRepository<T>
where T : class
where C : DbContext, new()
{
private C _entities = new C();
public C Context
{
get { return _entities; }
set { _entities = value; }
}
public virtual IQueryable<T> GetAll()
{
IQueryable<T> query = _entities.Set<T>();
return query;
}
public IQueryable<T> FindBy(System.Linq.Expressions.Expression<Func<T, bool>> predicate)
{
IQueryable<T> query = _entities.Set<T>().Where(predicate);
return query;
}
public virtual void Add(T entity)
{
_entities.Set<T>().Add(entity);
}
public virtual void Delete(T entity)
{
_entities.Set<T>().Remove(entity);
}
public virtual void Edit(T entity)
{
_entities.Entry(entity).State = System.Data.Entity.EntityState.Modified;
}
public virtual void Save()
{
_entities.SaveChanges();
}
}
我的所有实体都从这个类继承:
namespace Repository
{
public class StationRepository : GenericRepository<ShirazRailWay.ShirazRailwayEntities, DomainClass.Station>
{
}
}
我UI
我称这个存储库。正如你在这里看到的那样:
stationrepository objnew=new stationrepository();
obnew.getall();
在UI图层中,我在app.config
中有一个连接字符串,如您所见:
<connectionStrings>
<add name="ShirazRailwayEntities" connectionString="metadata=res://*/RailWay.csdl|res://*/RailWay.ssdl|res://*/RailWay.msl;provider=System.Data.SqlClient;provider connection string="data source=****;initial catalog=DB-Metro;user id=sa;password=****;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
但是我想为我的用户提供一个选项,通过这个选项,他们可以自己设置connection string
。所以我在UI层创建了一个表单,当用户试图log in
询问时他们是连接字符串。我的问题是How can pass this connection string to my dbcontext
?
在我的model layer(dbcontext)
我有这个:
public partial class ShirazRailwayEntities : DbContext
{
public ShirazRailwayEntities()
: base("name=ShirazRailwayEntities")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public DbSet<Advertisement> Advertisements { get; set; }
public DbSet<Line> Lines { get; set; }
public DbSet<Log> Logs { get; set; }
public DbSet<Path> Paths { get; set; }
public DbSet<Sensor> Sensors { get; set; }
public DbSet<Station> Stations { get; set; }
public DbSet<Train> Trains { get; set; }
public DbSet<User> Users { get; set; }
public DbSet<TimeTable> TimeTables { get; set; }
public DbSet<ConfigFont> ConfigFonts { get; set; }
public DbSet<ArrivalTime> ArrivalTimes { get; set; }
public DbSet<ConfigColor> ConfigColors { get; set; }
}
答案 0 :(得分:3)
添加另一个带有连接字符串的构造函数:
public partial class ShirazRailwayEntities : DbContext
{
public ShirazRailwayEntities()
: base(name: "ShirazRailwayEntities")
{
}
public ShirazRailwayEntities(string connectionName)
: base(name: connectionName)
{
}
}
var context = new ShirazRailwayEntities("whatever connection name you want");