注意一点:
在EF中使用事物后,对于一个新增的model,在saveChanges后,可以得到该实体的自增ID,但在提交事物之前,
该数据并没有真正的新增到DB中,但此时可以得到model新增的自增ID,程序中可以使用,很方便!
例如下面的series实体在新增时,下面新增level时就可以直接使用,但此时的series并没有真正的新增到db中。
/// <summary>
/// 导入汽车维护数据
/// </summary>
/// <param name="BrandName"></param>
/// <returns></returns>
public static Result ImportVehicleData(string strDataTable)
{
DataTable dt = JsonHelper.Deserialize<DataTable>(strDataTable);
if (dt != null)
{
using (Entities db = new Entities())
{
using (TransactionScope transaction = new TransactionScope())
{
try
{
var brandList = db.TL_Sys_VehicleBrand.ToList();
var seriesList = db.TL_Sys_VehicleSeries.ToList();
var levelList = db.TL_Sys_VehicleLevel.ToList();
string brandName = "";
string seriesName = "";
string levelName = "";
bool isInterest = true;
bool isDefault = true;
TL_Sys_VehicleBrand brand = new TL_Sys_VehicleBrand();
TL_Sys_VehicleSeries series = new TL_Sys_VehicleSeries();
bool isSave = false;
foreach (DataRow dr in dt.Rows)
{
brandName = dr[0].ToString().Trim();
isInterest = dr[3].ToString().Trim() == "否" ? false : true;
isDefault = dr[4].ToString().Trim() == "否" ? false : true;
brand = brandList.Where(p => p.Name == brandName).FirstOrDefault();
seriesName = dr[1].ToString().Trim();
series = seriesList.Where(p => p.CarBrandID == brand.ID && p.Name.Trim().Replace(" ", "") == seriesName.Trim().Replace(" ", "")).FirstOrDefault();
if (series == null)
{
series = new TL_Sys_VehicleSeries();
//新增车辆车系
series.CarBrandID = brand.ID;
series.Name = seriesName;
series.Code = GetVehicleSeriesNextCode(brand, seriesList);
series.IsInterest = isInterest;
series.IsDefault = isDefault;
db.TL_Sys_VehicleSeries.Add(series);
db.SaveChanges();
seriesList.Add(series);
}
levelName = dr[2].ToString().Trim();
if (!string.IsNullOrWhiteSpace(levelName) && series != null && series.ID > 0)
{
var level = levelList.Where(p => p.CarLineID == series.ID && p.Name.Trim().Replace(" ", "") == levelName.Trim().Replace(" ", "")).FirstOrDefault();
if (level == null)
{
level = new TL_Sys_VehicleLevel();
//新增车辆车型
level.CarLineID = series.ID;
level.Name = levelName;
level.Code = GetVehicleLevelNextCode(series, levelList);
level.IsInterest = isInterest;
level.IsDefault = isDefault;
db.TL_Sys_VehicleLevel.Add(level);
//db.SaveChanges();
isSave = true;
levelList.Add(level);
}
}
}
//如果有新增的车型,就一起保存数据库
if (isSave)
{
db.SaveChanges();
}
transaction.Complete();
return new Result(true, "导入成功");
}
catch(Exception er)
{
transaction.Dispose();
return new Result(false, "导入发生异常," + er.ToString());
}
}
}
}
return new Result(false, "导入汽车信息不能为空");
}