[英]How can I make my console application more reusable across different databases?
Take for example the pubs database and the employee table. 以pubs数据库和employee表为例。 I have the following contrived example that reads batches of employees and just updates the last name column using Entity Framework 6.0
. 我有以下精心设计的示例,该示例读取成批的员工并仅使用Entity Framework 6.0
更新姓氏列。
Let's say I want to use this to update employee information in the Northwind database. 假设我要用它来更新Northwind数据库中的员工信息。 Is there a good way to do this without creating 2 different programs because what if another similar employee table in a different database would require a third console application. 是否有一个好的方法可以在不创建2个不同程序的情况下执行此操作,因为如果不同数据库中的另一个相似的employee表将需要第三个控制台应用程序怎么办?
Assume that the fields are the same across the different databases but could have different names for fields. 假设不同数据库中的字段相同,但字段名称可能不同。
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();
}
}
}
}
}
}
You could consider the Repository Pattern. 您可以考虑使用存储库模式。 See: https://www.infoworld.com/article/3107186/how-to-implement-the-repository-design-pattern-in-c.html as a sample article. 请参阅: https : //www.infoworld.com/article/3107186/how-to-implement-the-repository-design-pattern-in-c.html作为示例文章。
In general, the repository pattern's goal is to separate data persistence from business logic. 通常,存储库模式的目标是将数据持久性与业务逻辑分离。 If you have different databases underneath, you would still need at least 2 sets of repository code, but the business logic that sits on top of it would, in theory, not care. 如果下面有不同的数据库,则仍然需要至少两组存储库代码,但是从理论上讲,位于其上的业务逻辑将不在乎。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.