C# EF+LINQ保存主从表数据
C# 全选
/// <summary>
/// 保存主从表数据
/// </summary>
public SaveResult Update(BusinessData<tb_BOM, tb_BOMList> data)
{
//检查BOM产品重复定义
if (data.Master.BOMID.IsEmpty() || data.Master.BOMID == "*自动生成*")
{
var exists = _Database.GetQueryable<tb_BOM>().Any(a => a.OwnerProductCode == data.Master.OwnerProductCode);
if (exists) throw new CustomException("BOM产品重复定义!");
}
try
{
_Database.BeginTransaction();
SetCommonValue<tb_BOM>(new List<tb_BOM> { data.Master });
SetCommonValue<tb_BOMList>(data.Details);
//判断单据号码是否已存在,即可识别当前操作是新增或修改状态
var m = _Database.GetQueryable<tb_BOM>();
var isEdit = m.Any(a => a.BOMID == data.Master.BOMID);//修改状态
var isAdd = isEdit == false;//新增状态
if (isAdd)
{
#region 新增状态
//获取单据号码
data.Master.BOMID = DocNoHelper.GetDocNo(_Database, "BO", _Loginer.Account);
//设置明细表外键
foreach (var d in data.Details)
{
d.BOMID = data.Master.BOMID;
}
_Database.Add<tb_BOM>(data.Master);
_Database.Add<tb_BOMList>(data.Details);
#endregion
}
else
{
#region 修改状态
//保存主表
_Database.Update<tb_BOM>(data.Master);
//保存明细:先删除明细,再新增
_Database.Remove<tb_BOMList>(w => w.BOMID == data.Master.BOMID);
_Database.Add(data.Details);
#endregion
}
_Database.CommitTransaction();
_Log.Log(DataLogType.save, "BOM保存", nameof(tb_BOM), "", _Loginer.Account, data);
var result = new SaveResult
{
DocNo = data.Master.BOMID,//单据号码
Result = (int)ResultID.SUCCESS,//成功状态
Description = "保存成功",
};
return result;
}
catch (Exception ex)
{
_Database.RollbackTransaction();
//数据操作日志
_Log.Log(DataLogType.exception, "BOM保存失败!" + ex.GetMessage(), nameof(tb_BOM), "", _Loginer.Account, data);
throw;
}
}
版权声明:本文为开发框架文库发布内容,转载请附上原文出处连接
CSFramework.EF C/S框架网