我正在使用EF5
将一些数据从一个数据库迁移到另一个数据库。我通常会使用SQL
这样的东西,但是我需要其他功能(比如在MembershipProvider
中创建用户)并希望在EF中完成所有操作。我正在迁移大约10万行并使用它来执行此操作:
using (var connection = new SqlConnection(connectionString))
{
using(var command = new SqlCommand(commandText, connection))
{
connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
var employer = new Employer();
employer.EAN = reader["EAN"].ToString();
employer.Name = GetString(reader["EmpName"]);
employer.TaxMailingAddress = new Address
{
StreetAddress = GetString(reader["Street"]),
City = GetString(reader["City"]),
State = GetString(reader["USState"]),
ZipCode = GetString(reader["Zip"])
};
employer.TaxMailingAddress.SaveOrUpdate();
employer.SaveOrUpdate(); // This is where the timeout happens
string dba = GetString(reader["DBA"]);
if (!string.IsNullOrWhiteSpace(dba))
{
employer.AddDBA(new EmployerDba
{
Name = dba
});
}
string email = GetString(reader["Email"]);
if (!string.IsNullOrWhiteSpace(email))
{
var user = CreateNewUser(email);
if (user != null)
{
user.AddAuthorizedEmployer(employer);
user.AddRole(EmployerRole.Admin, employer, true);
}
}
}
}
}
}
我的SaveOrUpdate
方法很简单:
public void SaveOrUpdate()
{
using (var db = new MyContext())
{
if (db.Employers.FirstOrDefault(x => x.EAN == EAN && x.Id != Id) != null)
throw new Exception("An employer with this EAN has already been registered.");
var employer = new Employer();
if (Id == 0)
{
db.Employers.Add(employer);
employer.CreatedBy = Statics.GetCurrentUserName();
employer.DateCreated = DateTime.Now;
}
else
{
employer = db.Employers.FirstOrDefault(x => x.Id == Id);
employer.ModifiedBy = Statics.GetCurrentUserName();
employer.DateModified = DateTime.Now;
}
employer.EAN = EAN;
employer.Name = Name;
if (TaxMailingAddress != null) employer.TaxMailingAddress = db.Addresses.FirstOrDefault(x => x.Id == TaxMailingAddress.Id);
if (SingleSeparationStatementAddress != null) employer.SingleSeparationStatementAddress = db.Addresses
.FirstOrDefault(x => x.Id == SingleSeparationStatementAddress.Id);
db.SaveChanges();
Id = employer.Id;
}
}
任务大约需要2.5小时才能完成。但是,在运行了数千行,有时80k,有时只有7k,我得到"The wait operation timed out"
异常,总是在employer.SaveOrUpdate();
上。它与employer.TaxMailingAddress.SaveOrUpdate();
的接近程度有什么关系吗?是否有“等待交易完成”的交易?也许确保连接有效,如果没有尝试重新创建它或什么?谢谢你的帮助。
答案 0 :(得分:3)
问题最终是我的初始数据库连接用于连接到另一个数据库,我从中获取要导入的数据,这个数据库连接是超时的。所以我最终循环遍历所有reader.Read()
语句并将其放入数组中。然后我循环遍历该数组以实际处理并将数据保存到我的新数据库中。