以pubs数据库和employee表为例。我有以下设计的示例,它读取批量员工,只使用Entity Framework 6.0
更新姓氏列。
假设我想用它来更新Northwind数据库中的员工信息。有没有一种很好的方法可以在不创建2个不同程序的情况下执行此操作,因为如果另一个数据库中的另一个类似的员工表需要第三个控
假设不同数据库中的字段相同,但字段的名称可能不同。
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
namespace EFTransactionConsoleApplication
{
class Program
{
static void Main(string[] args)
{
using (pubsEntities dbContext = new pubsEntities())
{
using (DbContextTransaction transaction = dbContext.Database.BeginTransaction())
{
IEnumerable<employee> employees = null;
int currentPage = 1;
int totalPages = dbContext.employees.Count();
string lastEmpId = string.Empty;
try
{
do
{
employees = (from x in dbContext.employees
where string.Compare(x.emp_id, lastEmpId) > 0
orderby x.emp_id
select x).Take(5).ToList();
if (employees.Count() > 0)
{
lastEmpId = employees.Last().emp_id;
//var fifthEmp = dbContext.employees.Where(x => x.emp_id == lastEmpId).FirstOrDefault();
//fifthEmp.lname += "test";
dbContext.Database.ExecuteSqlCommand(@"
UPDATE employee SET lname = " + "'test 123'" + " WHERE emp_id = '" + lastEmpId + "'"
);
//foreach (var item in employees)
//{
// Console.WriteLine("{0}-{1}", item.emp_id, item.fname);
//}
//dbContext.SaveChanges();
}
if (currentPage == 6)
throw new Exception("Error occurred");
currentPage++;
} while (currentPage <= totalPages);
transaction.Commit();
}
catch (Exception)
{
transaction.Rollback();
}
}
}
}
}
}
您可以考虑存储库模式。请参阅:https://www.infoworld.com/article/3107186/how-to-implement-the-repository-design-pattern-in-c.html作为样本文章。
通常,存储库模式的目标是将数据持久性与业务逻辑分开。如果你下面有不同的数据库,你仍然需要至少2套存储库代码,但理论上,处理它的业务逻辑无关紧要。