我首先使用了EF6代码,并为每个数据库创建了一个上下文,我希望每个CRUD操作能够在不明确提及的情况下调用数据库。
以下是我的两个背景:
public sealed class FiContext : DbContext {
public FiContext(string dataBase)
: base(GetDBConfiguration.GetFConfiguration(dataBase)) {
}
public DbSet<ClientsImported> ClientsImported { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder) {
}
}
public sealed class FranchiseeContext : DbContext {
public FranchiseeContext(string dataBase)
: base(GetDBConfiguration.GetConfiguration(dataBase)) {
}
public DbSet<Users> Users { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder) {
}
}
在这里,我想在我的数据库中插入一些数据:
public bool InsertInDataBase(string tableSql, string database, Table table) {
dynamic tableToObject = Utils.TableToObject(table);
List<string> resultNameList = tableToObject.ColumnName;
List<string> resultValueList = tableToObject.Value;
var dictionary = new Dictionary<string, string>();
for (int i = 0; i < resultNameList.Count; i++) {
dictionary.Add(resultNameList[i], resultValueList[i]);
}
switch (database.ToLower(CultureInfo.InvariantCulture)) {
case "franchisee":
using (var ctx = new FranchiseeContext (database)) {
var user = new Users();
foreach (var item in dictionary) {
var classPropertyType = user.GetType().GetProperty(item.Key).PropertyType;
var classPropertyName = user.GetType().GetProperty(item.Key);
var valueFromDictionary = dictionary[item.Key];
var valueFromDictionaryType = dictionary[item.Key].GetType();
if (classPropertyName != null) {
classPropertyName.SetValue(user,
classPropertyType != valueFromDictionaryType
? Convert(classPropertyType, valueFromDictionary)
: valueFromDictionary);
}
}
ctx.Users.Add(user);
ctx.SaveChanges();
return true;
}
case "fi":
using (var ctx = new FiContext(database)) {
var anafClients = new ANAFClientsImported();
foreach (var item in dictionary) {
var classPropertyType = anafClients.GetType().GetProperty(item.Key).PropertyType;
var classPropertyName = anafClients.GetType().GetProperty(item.Key);
var valueFromDictionary = dictionary[item.Key];
var valueFromDictionaryType = dictionary[item.Key].GetType();
if (classPropertyName != null) {
classPropertyName.SetValue(anafClients,
classPropertyType != valueFromDictionaryType
? Convert(classPropertyType, valueFromDictionary)
: valueFromDictionary);
}
}
ctx.ClientsImported.Add(Clients);
ctx.SaveChanges();
return true;
}
}
return false;
}