Linq 调试
void Main() {
var MyMonitor = new Devart.Data.Oracle.OracleMonitor();
MyMonitor.IsActive = true;
var faker = new RiaInvokeDataFaker(@"E:\软件\Linq20160126\LINQPad.xp510.com\LINQPad\修改备件采购订单.xml", "修改备件采购订单");
using (var transaction = new TransactionScope()) {
var order = faker.GetEntity<PartsPurchaseOrder>("partsPurchaseOrder");
order.RowVersion = this.PartsPurchaseOrders.Where(p => p.Id == order.Id).SetMergeOption(MergeOption.NoTracking).First().RowVersion;
new PartsPurchaseOrderAch(new DcsDomainService(this)).修改备件采购订单(order,
faker.GetList<PartsPurchaseOrderDetail>("partsPurchaseOrderDetails"),
faker.GetList<PurchasePlanDetail>("purchasePlanDetails").ToArray());
}
} partial class PartsPurchaseOrderAch : DcsSerivceAchieveBase {
public PartsPurchaseOrderAch(DcsDomainService domainService)
: base(domainService) {
} public void 修改备件采购订单(PartsPurchaseOrder partsPurchaseOrder, IEnumerable<PartsPurchaseOrderDetail> partsPurchaseOrderDetails, PurchasePlanDetail[] purchasePlanDetails) {
this.修改配件采购订单私有(partsPurchaseOrder, partsPurchaseOrderDetails.ToList(), purchasePlanDetails.ToList());
} internal void 修改配件采购订单私有(PartsPurchaseOrder partsPurchaseOrder, List<PartsPurchaseOrderDetail> partsPurchaseOrderDetails, List<PurchasePlanDetail> purchasePlanDetails) {
this.UpdateToDatabase(partsPurchaseOrder);
var groupedSparCount = partsPurchaseOrderDetails.GroupBy(p => p.SparePartId).Count(c => c.Count() > 1);
if(groupedSparCount > 0)
throw new ValidationException("存在重复备件");
//查询最小订货单元
var detailsPartIds = purchasePlanDetails.Where(p => !p.IsSourceDetail).Select(p => p.SparePartId).Distinct();
var minOrderUnitsQuery = this.ObjectContext.MinOrderUnits.Where(m => detailsPartIds.Contains(m.PartId) && m.OrderKind == (int)DcsMinOrderUnitOrderKind.采购).ToArray();
//查询要货计划主单
var purchasePlanIds = purchasePlanDetails.Select(p => p.ParentId).Distinct();
var purchasePlans = ObjectContext.PurchasePlans.Include("PurchasePlanDetails").Where(p => purchasePlanIds.Contains(p.Id)).ToArray();
var dbPurchasePlanDetails = purchasePlans.SelectMany(p => p.PurchasePlanDetails).ToArray();
//查询配件采购价格
var sparePartIds = purchasePlanDetails.Select(v => v.SparePartId).Distinct();
var swapSparePartIds = purchasePlanDetails.Select(v => v.SwapSparePartId).Distinct().ToArray();
var partsPurchasePricings = this.ObjectContext.PartsPurchasePricings.Where(p => (sparePartIds.Contains(p.PartId) || swapSparePartIds.Contains(p.PartId)) && p.Status != (int)DcsPartsPurchasePricingStatus.作废).ToArray();
//查询配件FOB价格
var date = DateTime.Now;
var partsFOBs = this.ObjectContext.PartsFOBs.Where(f => sparePartIds.Contains(f.PartId) && f.BeginTime < date && f.EndTime > date).ToArray();
var olePartsPurchaseOrderDetails = ObjectContext.PartsPurchaseOrderDetails.Where(p => p.PartsPurchaseOrderId == partsPurchaseOrder.Id).ToList();
//处理配件采购订单清单 foreach(var detail in from groupedPlanDetail in
(from purchasePlanDetail in purchasePlanDetails.Where(p => !p.IsSourceDetail)
group purchasePlanDetail by new {
purchasePlanDetail.SparePartId,
purchasePlanDetail.SparePartCode
}
into planDetails
select new {
SumTheFiling = planDetails.Sum(p => p.TheFilings ?? 0),
planDetails.Key.SparePartId,
SparepartCode = planDetails.Key.SparePartCode
})
join oldPurchaseOrderDetail in olePartsPurchaseOrderDetails on groupedPlanDetail.SparePartId equals oldPurchaseOrderDetail.SparePartId into oldpartsPurchaseOrderDetails
from oldpartsPurchaseOrderDetail in oldpartsPurchaseOrderDetails.DefaultIfEmpty()
select new {
groupedPlanDetail,
oldpartsPurchaseOrderDetail
}) {
if(detail.oldpartsPurchaseOrderDetail == null)
throw new ValidationException(string.Format("{0}要货计划清单对应的采购订单清单不存在", detail.groupedPlanDetail.SparepartCode));
detail.oldpartsPurchaseOrderDetail.OrderAmount = detail.groupedPlanDetail.SumTheFiling;
if(detail.oldpartsPurchaseOrderDetail.OrderAmount == 0)
DeleteFromDatabase(detail.oldpartsPurchaseOrderDetail);
//else
// UpdateToDatabase(detail.oldpartsPurchaseOrderDetail);
} foreach(var detail in from planDetail in purchasePlanDetails.Where(p => p.IsSourceDetail)
group planDetail by new {
planDetail.ParentId,
planDetail.SwapSparePartId,
planDetail.SwapSparePartCode,
planDetail.SwapSparePartName,
planDetail.Price,
planDetail.CurType,
planDetail.FOBPrice
}
into planDetails
join olePurchaseOrderDetail in olePartsPurchaseOrderDetails on planDetails.Key.SwapSparePartId equals olePurchaseOrderDetail.SparePartId into olePurchaseOrderDetails
from partsPurchaseOrderDetail in olePurchaseOrderDetails.DefaultIfEmpty()
join purchasePricing in partsPurchasePricings on planDetails.Key.SwapSparePartId equals purchasePricing.PartId into purchasePricings
from partsPurchasePricing in purchasePricings.DefaultIfEmpty()
join minOrderUnitQuery in minOrderUnitsQuery on planDetails.Key.SwapSparePartId equals minOrderUnitQuery.PartId into minOrderUnits
from minOrderUnit in minOrderUnits.DefaultIfEmpty()
join purchasePlan in purchasePlans on planDetails.Key.ParentId equals purchasePlan.Id
select new {
planDetails,
purchasePlan,
partsPurchaseOrderDetail,
partsPurchasePricing,
minOrderUnit
}) {
var purchasePlanDetail = detail.planDetails.First();
var sumTheFilings = detail.planDetails.Sum(p => p.TheFilings ?? 0);
if(detail.partsPurchaseOrderDetail != null) {
detail.partsPurchaseOrderDetail.OldOrderAmount += detail.partsPurchaseOrderDetail.OrderAmount;
detail.partsPurchaseOrderDetail.OrderAmount += sumTheFilings; UpdateToDatabase(detail.partsPurchaseOrderDetail);
} else {
if(detail.partsPurchasePricing == null)
throw new ValidationException("要货计划清单对应的配件采购价格不存在!");
var partsPurchaseOrderDetail = partsPurchaseOrderDetails.FirstOrDefault(p => p.SparePartId == purchasePlanDetail.SwapSparePartId); if(partsPurchaseOrderDetail == null) {
partsPurchaseOrderDetail = new PartsPurchaseOrderDetail() {
PartsPurchaseOrderId = partsPurchaseOrder.Id,
SparePartId = purchasePlanDetail.SwapSparePartId ?? 0,
SparePartCode = purchasePlanDetail.SwapSparePartCode,
SparePartName = purchasePlanDetail.SwapSparePartName,
UnitPrice = detail.partsPurchasePricing.PurchasePrice,
OrderAmount = sumTheFilings,
CurType = purchasePlanDetail.CurType,
FOBPrice = purchasePlanDetail.FOBPrice ?? 0,
pricepro = detail.partsPurchasePricing == null ? (int)DcsPartsPurchaseOrderDetailpricepro.暂估价 : detail.partsPurchasePricing.PriceType ?? 0,
MinQty = detail.minOrderUnit == null ? 0 : detail.minOrderUnit.MinQty,
SysQty = 0,
OldOrderAmount = 0,
ConfirmedAmount = 0,
};
partsPurchaseOrder.PartsPurchaseOrderDetails.Add(partsPurchaseOrderDetail);
partsPurchaseOrderDetails.Add(partsPurchaseOrderDetail);
var purchasePlansReverseList = new PartsPurOrderReverseList {
PartsPurchaseOrderDetail = partsPurchaseOrderDetail,
SpareId = partsPurchaseOrderDetail.SparePartId,
DataType = (int)DcsPurchasePlansReverseListDataType.新增,
Qty = 0
};
this.InsertToDatabase(purchasePlansReverseList);
} else {
partsPurchaseOrderDetail.OrderAmount += sumTheFilings;
} var purchasePlanAndOrderLink = new PurchasePlanAndOrderLink() {
PartsPurchaseOrder = partsPurchaseOrder,
PurchasePlanId = detail.purchasePlan.Id,
PurchasePlanDetail = purchasePlanDetail
};
partsPurchaseOrderDetail.PurchasePlanAndOrderLinks.Add(purchasePlanAndOrderLink);
this.InsertToDatabase(purchasePlanAndOrderLink);
}
} //更新要货计划清单 int nullValue = 0; //当int?类型值为null时的替代值,一般此值不会被实际应用。
var tempDetails = from planDetail in purchasePlanDetails
join dbSwapPlanDetail in dbPurchasePlanDetails on new {
planDetail.ParentId,
SparePartId = planDetail.SwapSparePartId ?? 0
} equals new {
dbSwapPlanDetail.ParentId,
dbSwapPlanDetail.SparePartId
} into planDetails
from dbSwapPlanDetail in planDetails.DefaultIfEmpty()
join dbPlanDetail in dbPurchasePlanDetails on new {
planDetail.ParentId,
planDetail.SparePartId
} equals new {
dbPlanDetail.ParentId,
dbPlanDetail.SparePartId
} into oldplanDetails
from dbPlanDetail in oldplanDetails.DefaultIfEmpty() join fob in partsFOBs on new {
SwapSparePartId = planDetail.SwapSparePartId ?? 0,
CurType = planDetail.CurType ?? 0
} equals new {
SwapSparePartId = fob.PartId,
CurType = fob.CurrencyKind
} into fobs
from fob in fobs.DefaultIfEmpty()
//join purchasePlan in purchasePlans on planDetail.ParentId equals purchasePlan.Id into purPlans
//from purchasePlan in purPlans.DefaultIfEmpty()
join minOrderUnit in minOrderUnitsQuery on planDetail.SparePartId equals minOrderUnit.PartId into minOrderUnits
from minOrderUnit in minOrderUnits.DefaultIfEmpty()
join purchasePricing in partsPurchasePricings on planDetail.SwapSparePartId equals purchasePricing.PartId into purchasePricings
from partsPurchasePricing in purchasePricings.DefaultIfEmpty()
select new {
planDetail,
dbSwapPlanDetail,
dbPlanDetail, minOrderUnit,
partsPurchasePricing,
partFOB = fob,
//purchasePlan
};
foreach(var detail in tempDetails) {
if(detail.planDetail.IsSourceDetail) {
var purchasePlan = purchasePlans.FirstOrDefault(p => p.Id == detail.planDetail.ParentId);
if(purchasePlan == null)
throw new ValidationException("要货计划清单对应的要货计划单不存在");
if(detail.dbSwapPlanDetail != null) {
detail.dbSwapPlanDetail.PlanQty += detail.planDetail.TheFilings ?? 0;
UpdateToDatabase(detail.dbSwapPlanDetail);
} else {
if(detail.partsPurchasePricing == null)
throw new ValidationException(string.Format("备件[{0}]合同价已失效!", detail.planDetail.SwapSparePartCode));
detail.planDetail.SparePartId = detail.planDetail.SwapSparePartId ?? 0;
detail.planDetail.SparePartCode = detail.planDetail.SwapSparePartCode;
detail.planDetail.SparePartName = detail.planDetail.SwapSparePartName;
detail.planDetail.MinQty = detail.minOrderUnit == null ? nullValue : detail.minOrderUnit.MinQty;
detail.planDetail.SysQty = 0;
detail.planDetail.Price = detail.partsPurchasePricing.PurchasePrice;
detail.planDetail.FOBPrice = detail.partFOB == null ? 0 : detail.partFOB.Price;
detail.planDetail.FirstQty = detail.planDetail.TheFilings ?? 0;
detail.planDetail.PlanQty = detail.planDetail.TheFilings ?? 0;
purchasePlan.PurchasePlanDetails.Add(detail.planDetail);
UpdateToDatabase(purchasePlan);
new PurchasePlanAch(this.DomainService).UpdatePurchasePlanValidate(detail.planDetail.PurchasePlan);
var purchasePlansReverseList = new PurchasePlansReverseList {
PurchasePlanDetail = detail.planDetail,
SpareId = detail.planDetail.SparePartId,
DataType = (int)DcsPurchasePlansReverseListDataType.新增,
Qty = 0
};
this.InsertToDatabase(purchasePlansReverseList);
}
} else {
if(!swapSparePartIds.Contains(detail.planDetail.SparePartId)) {
detail.dbPlanDetail.PlanQty = detail.planDetail.TheFilings ?? 0;
//UpdateToDatabase(detail.oldPartsPurchasePlanDetail);
}
}
if(detail.planDetail.TheFilings == 0 || !detail.planDetail.TheFilings.HasValue) {
DeleteFromDatabase(detail.dbPlanDetail);
}
} //更新要货计划主单
foreach(var purchasePlan in purchasePlans) {
purchasePlan.SumPrice = purchasePlan.PurchasePlanDetails.Sum(d => d.PlanQty * d.Price);
purchasePlan.FOBPrice = purchasePlan.PurchasePlanDetails.Sum(d => d.PlanQty * d.FOBPrice);
//this.UpdateToDatabase(purchasePlan);
new PurchasePlanAch(this.DomainService).UpdatePurchasePlanValidate(purchasePlan);
} //处理累计订货量
List<VirtualBillDetail> virtualBillDetails = purchasePlanDetails.Select(detail => new VirtualBillDetail() {
OppositeSideUnitId = partsPurchaseOrder.PartsSupplierId,
清单备件Id = detail.IsSourceDetail? detail.SwapSparePartId.Value:detail.SparePartId,
清单备件编号 =detail.IsSourceDetail? detail.SwapSparePartCode:detail.SparePartCode,
清单原数量 = detail.IsSourceDetail ? 0 : detail.PlanQty,
清单倒冲后数量 = detail.TheFilings ?? 0
}).ToList();
if(partsPurchaseOrder.Status == (int)DcsPartsPurchaseOrderStatus.已确认) { this.倒冲累计订货量(virtualBillDetails, partsPurchasePricings, true);
} this.倒冲累计订货量(virtualBillDetails, partsPurchasePricings); //更新采购订单主单
partsPurchaseOrder.TotalAmount = partsPurchaseOrder.PartsPurchaseOrderDetails.Sum(d => d.UnitPrice * (d.OrderAmount));
var count = partsPurchaseOrderDetails.Count;
var d0 = partsPurchaseOrderDetails.Count(d => d.ConfirmedAmount > 0);
partsPurchaseOrder.KindRate = d0 / count;
partsPurchaseOrder.QtyRate = partsPurchaseOrderDetails.Sum(d => d.ConfirmedAmount) / partsPurchaseOrderDetails.Sum(d => d.OrderAmount);
partsPurchaseOrder.SumTax = (double)partsPurchaseOrder.PartsPurchaseOrderDetails.Sum(p => ((p.OrderAmount) * p.UnitPrice) * (decimal)0.17);
partsPurchaseOrder.IsMinOrderUnit = true;
this.SetMofifyInfo(partsPurchaseOrder);
if(partsPurchaseOrder.Status == (int)DcsPartsPurchaseOrderStatus.审核不通过)
partsPurchaseOrder.Status = (int)DcsPartsPurchaseOrderStatus.新增;
// UpdateToDatabase(partsPurchaseOrder);
this.UpdatePartsPurchaseOrderValidate(partsPurchaseOrder);
this.ObjectContext.SaveChanges();
} internal void 倒冲累计订货量(List<VirtualBillDetail> virtualBillDetails, IEnumerable<PartsPurchasePricing> partsPurchasePricings = null, bool is更新累计检验量 = false) { if(virtualBillDetails == null || !virtualBillDetails.Any())
return;
/*
1、如果 配件合同价=空, 则 调用服务:查询配件采购价格,依据:(配件采购价格.配件Id, 配件采购价格.配件供应商Id) in ((传入单据清单.[清单配件Id字段名称],传入单据主单.[主单对方单位Id字段名称])数组) 且 状态=生效 且 生效时间<当前时间 且 失效时间>当前时间。
*/
var SID = virtualBillDetails.FirstOrDefault().OppositeSideUnitId;
if(partsPurchasePricings == null) { var partIdsQuery = from detail in virtualBillDetails
select new {
id = detail.清单备件Id
};
partsPurchasePricings = new PartsPurchasePricingAch(this.DomainService).依据备件名称与供应商ID查询配件采购价格(partIdsQuery.Select(s => s.id).ToArray(), SID).ToList();
}
/*
2、循环传入单据清单,
在配件合同价中定位,定位依据:配件合同价.配件Id=传入单据清单.[清单配件Id字段名称] 且 配件合同价.配件供应商Id=传入单据主单.[主单对方单位Id字段名称]
如果存在,
如果 配件合同价.备件累计已订货数量+传入单据清单.[清单倒冲后数量字段名称]-传入单据清单.[清单原数量字段名称]>配件合同价.备件最大订货数量,则提示错误:“备件[传入单据清单.[备件编号字段名称]]最大订货数量为[配件采购价格.备件最大订货数量],累计订货数量为[配件采购价格.备件累计已订货数量],本次新增数量为[传入单据清单.[清单倒冲后数量字段名称]-传入单据清单.[清单原数量字段名称]],已超过最大订货数量,请修改本次订货数量!”
赋值:配件采购价格.备件累计已订货数量=配件合同价.备件累计已订货数量+传入单据清单.[清单倒冲后数量字段名称]-传入单据清单.[清单原数量字段名称]
*/
var errorInfo = new StringBuilder();
foreach(var detail in from virtualBillDetail in virtualBillDetails
join purchasePricing in partsPurchasePricings on new {
PartId = virtualBillDetail.清单备件Id
} equals new {
purchasePricing.PartId
} into purchasePricings
from partsPurchasePricing in purchasePricings.DefaultIfEmpty()
select new {
virtualBillDetail,
partsPurchasePricing,
}) {
if(detail.partsPurchasePricing != null) {
if(!is更新累计检验量) {
if(detail.partsPurchasePricing.MaxOrderQty != 0 && (detail.partsPurchasePricing.UsedOrderQty + detail.virtualBillDetail.清单倒冲后数量 - detail.virtualBillDetail.清单原数量) > detail.partsPurchasePricing.MaxOrderQty) {
errorInfo.AppendLine(string.Format("备件[{0}]最大订货数量为[{1}],累计订货数量为[{2}],本次新增数量为([" + (detail.virtualBillDetail.清单倒冲后数量 - detail.virtualBillDetail.清单原数量) + "]),已超过最大订货数量,请修改本次订货数量!", detail.virtualBillDetail.清单备件编号, detail.partsPurchasePricing.MaxOrderQty, detail.partsPurchasePricing.UsedOrderQty, detail.virtualBillDetail.清单倒冲后数量, detail.virtualBillDetail.清单原数量));
continue;
}
if(detail.virtualBillDetail.清单备件编号 == "GP9A34200C")
throw new ValidationException((detail.partsPurchasePricing.UsedOrderQty ?? 0) + detail.virtualBillDetail.清单倒冲后数量 - detail.virtualBillDetail.清单原数量 + " 累计订货量 " + detail.partsPurchasePricing.UsedOrderQty + " 清单倒冲后数量 " + detail.virtualBillDetail.清单倒冲后数量 + " 清单原数量 " + detail.virtualBillDetail.清单原数量 + detail.virtualBillDetail.清单备件编号);
detail.partsPurchasePricing.UsedOrderQty = (detail.partsPurchasePricing.UsedOrderQty ?? 0) + detail.virtualBillDetail.清单倒冲后数量 - detail.virtualBillDetail.清单原数量;
} else {
detail.partsPurchasePricing.UsedVerifyQty = (detail.partsPurchasePricing.UsedVerifyQty ?? 0) + detail.virtualBillDetail.清单倒冲后数量 - detail.virtualBillDetail.清单原数量;
}
this.UpdateToDatabase(detail.partsPurchasePricing);
} else {
throw new ValidationException(string.Format("{0}不存在配件采购价格",detail.virtualBillDetail.清单备件编号));
}
if(errorInfo.Length > 0)
throw new ValidationException(errorInfo.ToString());
//3、调用服务:更新配件采购价格。 }
} internal void UpdatePartsPurchaseOrderValidate(PartsPurchaseOrder partsPurchaseOrder) {
if (!string.IsNullOrEmpty(partsPurchaseOrder.SuppOrderCode))
partsPurchaseOrder.SuppOrderCode = partsPurchaseOrder.SuppOrderCode.ToUpper();
var userInfo = Utils.GetCurrentUserInfo();
partsPurchaseOrder.ModifierId = userInfo.Id;
partsPurchaseOrder.ModifierName = userInfo.Name;
partsPurchaseOrder.ModifyTime = DateTime.Now;
}
} partial class PurchasePlanAch : DcsSerivceAchieveBase {
public PurchasePlanAch(DcsDomainService service) : base(service) {
} internal void UpdatePurchasePlanValidate(PurchasePlan purchasePlan) {
var userInfo = Utils.GetCurrentUserInfo();
purchasePlan.ModifierId = userInfo.Id;
purchasePlan.ModifierName = userInfo.Name;
purchasePlan.ModifyTime = DateTime.Now;
}
} partial class PartsPurchasePricingAch : DcsSerivceAchieveBase {
public PartsPurchasePricingAch(DcsDomainService service) : base(service) {
} public IQueryable<PartsPurchasePricing> 依据备件名称与供应商ID查询配件采购价格(int[] sparePartIds, int supplierId) {
return this.ObjectContext.PartsPurchasePricings.Where(p => sparePartIds.Contains(p.PartId) && p.PartsSupplierId == supplierId && p.Status == (int)DcsPartsPurchasePricingStatus.生效);
}
} partial class DcsDomainService : System.ServiceModel.DomainServices.EntityFramework.LinqToEntitiesDomainService<DcsEntities> {
protected override DcsEntities CreateObjectContext() {
// return new DcsEntities(new EntityConnection());
return entities;
} private DcsEntities entities; public DcsDomainService(DcsEntities dcsEntities) : base() {
entities = dcsEntities;
} internal void InsertToDatabase(EntityObject entity) {
if (entity.EntityState != System.Data.EntityState.Detached)
ObjectContext.ObjectStateManager.ChangeObjectState(entity, System.Data.EntityState.Added);
else {
switch (entity.GetType().Name) {
case "ABCStrategy":
ObjectContext.ABCStrategies.AddObject((ABCStrategy)entity);
break;
default:
throw new NotImplementedException(string.Format(notImplementMsg, entity.GetType().Name, "add"));
}
}
} private void UpdateToDatabase<T>(ObjectSet<T> objectSet, T entity) where T : class {
if (ChangeSet == null || !ChangeSet.ChangeSetEntries.Any(e => ReferenceEquals(e.Entity, entity))) {
objectSet.AttachAsModified(entity);
return;
}
var original = ChangeSet.GetOriginal(entity);
if (original == null)
objectSet.AttachAsModified(entity);
else
objectSet.AttachAsModified(entity, original);
} private readonly string notImplementMsg = "上面没有实现{0}的{1}方法,自己实现一下吧"; internal void UpdateToDatabase(EntityObject entity) {
var entityName = entity.GetType().Name;
switch (entityName) {
case "ABCStrategy":
UpdateToDatabase(ObjectContext.ABCStrategies, (ABCStrategy)entity);
break;
// case "PartsPurchaseOrderDetail":
// UpdateToDatabase(ObjectContext.PartsPurchaseOrderDetails, (PartsPurchaseOrderDetail)entity);
// break;
// case "PurchasePlanDetail":
// UpdateToDatabase(ObjectContext.PurchasePlanDetails, (PurchasePlanDetail)entity);
// break;
case "PartsPurchaseOrder":
UpdateToDatabase(ObjectContext.PartsPurchaseOrders, (PartsPurchaseOrder)entity);
break;
default:
throw new NotImplementedException(string.Format(notImplementMsg, entityName, "update"));
}
} private void DeleteFromDatabase<T>(ObjectSet<T> objectSet, T entity) where T : class {
objectSet.Attach(entity);
objectSet.DeleteObject(entity);
} internal void DeleteFromDatabase(EntityObject entity) {
if (entity.EntityState == System.Data.EntityState.Added)
ObjectContext.ObjectStateManager.ChangeObjectState(entity, System.Data.EntityState.Detached);
else if (entity.EntityState != System.Data.EntityState.Detached)
ObjectContext.ObjectStateManager.ChangeObjectState(entity, System.Data.EntityState.Deleted);
else {
// ObjectContext.DeleteObject(entity);
switch (entity.GetType().Name) {
case "ABCStrategy":
DeleteFromDatabase(ObjectContext.ABCStrategies, (ABCStrategy)entity);
break;
default:
throw new NotImplementedException(string.Format(notImplementMsg, entity.GetType().Name, "delete"));
}
}
} internal DcsEntities GetObjectContext() {
return this.ObjectContext;
} internal ChangeSet GetChangeSet() {
return this.ChangeSet;
}
} class DcsSerivceAchieveBase {
protected readonly DcsEntities ObjectContext;
protected IQueryable ParamQueryable = null;
protected Utils.UserInfo UserInfo; protected DcsSerivceAchieveBase(DcsDomainService service) {
DomainService = service;
ChangeSet = service.GetChangeSet();
ObjectContext = service.GetObjectContext();
UserInfo = Utils.GetCurrentUserInfo();
// this.ParamQueryable = service.ParamQueryable;
} public IEnumerable<KeyValueItem> GetKeyValueItems(string category, string name, bool? isBuiltIn) {
if (category == null)
throw new ArgumentNullException("category");
if (name == null)
throw new ArgumentNullException("name"); var result = this.ObjectContext.KeyValueItems.Where(kv => kv.Status != (int)DcsBaseDataStatus.作废 && kv.Category == category && kv.Name == name);
if (isBuiltIn != null)
result = result.Where(kv => kv.IsBuiltIn == isBuiltIn.Value);
return result;
} protected void CheckEntityState(EntityObject entity) {
if (ChangeSet.GetChangeOperation(entity) == ChangeOperation.Update && entity.EntityState == System.Data.EntityState.Added) {
ObjectContext.ObjectStateManager.ChangeObjectState(entity, System.Data.EntityState.Unchanged);
}
} protected DcsDomainService DomainService; protected ChangeSet ChangeSet; protected void InsertToDatabase(EntityObject entity) {
DomainService.InsertToDatabase(entity);
}
public string GetErrorFilePath(string fileName) {
return Path.Combine(Path.GetDirectoryName(fileName) ?? "", string.Format("{0}_ErrorData{1}", Path.GetFileNameWithoutExtension(fileName), Path.GetExtension(fileName)));
} public string GetExportFilePath(string fileName) {
var enterpriseCode = Utils.GetCurrentUserInfo().EnterpriseCode;
return Path.Combine(GlobalVar.DOWNLOAD_EXPORTFILE_DIR, enterpriseCode, string.Format("{0}_{1:yyMMdd_HHmmss_fff}{2}", Path.GetFileNameWithoutExtension(fileName), DateTime.Now, Path.GetExtension(fileName)));
} public string GetImportFilePath(string fileName) {
return fileName;
}
protected void UpdateToDatabase(EntityObject entity) {
DomainService.UpdateToDatabase(entity);
} protected void DeleteFromDatabase(EntityObject entity) {
DomainService.DeleteFromDatabase(entity);
} /// <summary>
/// 赋与实体更新时必要的信息
/// </summary>
/// <typeparam name="T">实体类型</typeparam>
/// <param name="entity">实体</param>
protected void SetMofifyInfo<T>(T entity) where T : EntityObject {
SetMofifyInfo(entity, UserInfo);
} /// <summary>
/// 赋与实体更新时必要的信息
/// </summary>
/// <typeparam name="T">实体类型</typeparam>
/// <param name="entity">实体</param>
/// <param name="userInfo">用户信息</param>
protected void SetMofifyInfo<T>(T entity, Utils.UserInfo userInfo) where T : EntityObject {
foreach (var pro in entity.GetType().GetProperties()) {
switch (pro.Name.ToLower()) {
case "modifierid":
pro.SetValue(entity, userInfo.Id, null);
break;
case "modifiername":
pro.SetValue(entity, userInfo.Name, null);
break;
case "modifytime":
pro.SetValue(entity, DateTime.Now, null);
break;
}
}
} /// <summary>
/// 赋与实体创建时必要的信息
/// </summary>
/// <typeparam name="T">实体类型</typeparam>
/// <param name="entity">实体</param>
protected void SetCreateInfo<T>(T entity) where T : EntityObject {
SetCreateInfo(entity, UserInfo);
} /// <summary>
/// 捕捉自定义Oracle报错,启用分布式事务后,在RAC类型的Oracle数据上抛自定义错误,错误内容无法抛出,所以暂时用此方法来捕获错误
/// </summary>
/// <param name="ex"></param>
protected void ThrowOracleException(Exception ex) {
//System.Data.EntityCommandExecutionException: 执行命令定义时出错。有关详细信息,请参阅内部异常。 ---> Devart.Data.Oracle.OracleException: ORA-20001: 该经销商账户可用余额不足!
var strSource = ex.ToString();
if (Regex.Match(strSource, @"ORA-20\d{3}").Success)
throw new ValidationException(ObjectContext.ExecuteStoreQuery<string>("select 'ORA' || errorId || ': ' || errormsg from tmp_error").FirstOrDefault());
throw new Exception(strSource);
} /// <summary>
/// 赋与实体创建时必要的信息
/// </summary>
/// <typeparam name="T">实体类型</typeparam>
/// <param name="entity">实体</param>
/// <param name="userInfo">用户信息</param>
protected void SetCreateInfo<T>(T entity, Utils.UserInfo userInfo) where T : EntityObject {
foreach (var pro in entity.GetType().GetProperties()) {
switch (pro.Name.ToLower()) {
case "creatorid":
pro.SetValue(entity, userInfo.Id, null);
break;
case "creatorname":
pro.SetValue(entity, userInfo.Name, null);
break;
case "createtime":
pro.SetValue(entity, DateTime.Now, null);
break;
}
}
} /// <summary>
/// 赋与实体作废时必要的信息
/// </summary>
/// <typeparam name="T">实体类型</typeparam>
/// <param name="entity">实体</param>
protected void SetAbandonInfo<T>(T entity) where T : EntityObject {
SetAbandonInfo(entity, UserInfo);
} /// <summary>
/// 赋与实体作废时必要的信息
/// </summary>
/// <typeparam name="T">实体类型</typeparam>
/// <param name="entity">实体</param>
/// <param name="userInfo">用户信息</param>
protected void SetAbandonInfo<T>(T entity, Utils.UserInfo userInfo) where T : EntityObject {
foreach (var pro in entity.GetType().GetProperties()) {
switch (pro.Name.ToLower()) {
case "abandonerid":
pro.SetValue(entity, userInfo.Id, null);
break;
case "abandonername":
pro.SetValue(entity, userInfo.Name, null);
break;
case "abandontime":
pro.SetValue(entity, DateTime.Now, null);
break;
}
}
} protected void SetApproveInfo<T>(T entity) where T : EntityObject {
SetApproveInfo(entity, UserInfo);
} /// <summary>
/// 赋与实体审批时必要的信息
/// </summary>
/// <typeparam name="T">实体类型</typeparam>
/// <param name="entity">实体</param>
/// <param name="userInfo">用户信息</param>
protected void SetApproveInfo<T>(T entity, Utils.UserInfo userInfo) where T : EntityObject {
foreach (var pro in entity.GetType().GetProperties()) {
switch (pro.Name.ToLower()) {
case "approverid":
pro.SetValue(entity, userInfo.Id, null);
break;
case "approvername":
pro.SetValue(entity, userInfo.Name, null);
break;
case "approvetime":
pro.SetValue(entity, DateTime.Now, null);
break;
}
}
} /// <summary>
/// 撤销所有服务端的修改
/// </summary>
protected void RejectChanges() {
var add = ObjectContext.ObjectStateManager.GetObjectStateEntries(System.Data.EntityState.Added);
foreach (var a in add)
ObjectContext.Detach(a.Entity); var modify = ObjectContext.ObjectStateManager.GetObjectStateEntries(System.Data.EntityState.Modified);
foreach (var m in modify)
for (int i = 0; i < m.OriginalValues.FieldCount; i++)
m.CurrentValues.SetValue(i, m.OriginalValues[i]); var delete = ObjectContext.ObjectStateManager.GetObjectStateEntries(System.Data.EntityState.Deleted);
foreach (var d in delete) {
var entity = d.Entity;
var entitySetName = d.EntitySet.Name;
ObjectContext.Detach(entity);
ObjectContext.AttachTo(entitySetName, entity);
}
ObjectContext.AcceptAllChanges();
}
} class RiaInvokeDataFaker {
//@"C:\Users\Anders\Documents\LINQPad Queries\数据\修改备件采购订单.xml","修改备件采购订单"
public RiaInvokeDataFaker(string filePath, string opreation) {
// string context;
// using (var fs = new FileStream(filePath, FileMode.Open, FileAccess.Read)) {
// TextReader tr = new StreamReader(fs, Encoding.UTF8);
// context = tr.ReadToEnd();
// context = context.Replace("xmlns=\"http://tempuri.org/\"", "");
// context = context.Replace("xmlns:a=\"http://schemas.datacontract.org/2004/07/Sunlight.Silverlight.Dcs.Web\"", "");
// context = context.Replace("<a:", "<");
// context = context.Replace("</a:", "</");
// }
xDoc = XDocument.Load(filePath);
xOpreation = xDoc.Element(xt + opreation);
} XNamespace xt = "http://tempuri.org/";
XNamespace xdcs = "http://schemas.datacontract.org/2004/07/" + typeof(UserQuery).BaseType.Namespace;
XNamespace xa = "http://schemas.microsoft.com/2003/10/Serialization/Arrays"; public T GetEntity<T>(string paramName) {
var xElementName = (typeof(T).IsSubclassOf(typeof(EntityObject)) ? xdcs : xa) + GetTypeName<T>();
return Deserialization<T>(paramName, xElementName);
} public Dictionary<TKey, TValue> GetDictionary<TKey, TValue>(string paramName) {
return Deserialization<Dictionary<TKey, TValue>>(paramName, xa + "ArrayOfKeyValueOf" + GetTypeName<TKey>() + GetTypeName<TValue>());
} private string GetTypeName<T>() {
var type = typeof(T);
return type == typeof(Int32) ? "int" : typeof(T).IsSubclassOf(typeof(EntityObject)) ? type.Name : type.Name.Substring(0, 1).ToLower() + type.Name.Substring(1);
} public List<T> GetList<T>(string paramName) {
return Deserialization<List<T>>(paramName, (typeof(T).IsSubclassOf(typeof(EntityObject)) ? xdcs : xa) + "ArrayOf" + GetTypeName<T>());
} private XDocument xDoc; private XElement xOpreation; T Deserialization<T>(string paramName, XName xElementName) {
using (var stream = new MemoryStream()) {
var xElement = xOpreation.Element(xt + paramName);
if (xElement == null)
throw new NullReferenceException("xml源中没有" + paramName);
xElement.Name = xElementName;
xElement.Save(stream);
stream.Position = 0;
return Deserialization<T>(stream);
}
} T Deserialization<T>(Stream stream) {
var serialzier = new System.Runtime.Serialization.DataContractSerializer(typeof(T));
return (T)serialzier.ReadObject(stream);
}
}
Linq 调试的更多相关文章
- Linqpad使用(调试Linq、结合linq调试业务场景、表格内编辑数据)
linqpad是一款linq语句调试工具,功能如下: 1.直接执行linq语句并查看生成的原生sql语句 2.可结合linq+C#代码进行业务场景调试 3.表格内直接新增.修改.删除数据 4.直接 ...
- Linq调试实时输出信息扩展方法(摘抄)
原文在此 [译]如何在C#中调试LINQ查询 原linq语句: var res = employees .Where(e => e.Gender == "Male") .Ta ...
- 如何在C#中调试LINQ查询
原文:How to Debug LINQ queries in C# 作者:Michael Shpilt 译文:如何在C#中调试LINQ查询 译者:Lamond Lu 在C#中我最喜欢的特性就是LIN ...
- 10个用于C#.NET开发的基本调试工具
在调试软件时,工具非常重要.获取正确的工具,然后再调试时提起正确的信息.根据获取的正确的错误信息,可以找到问题的根源所在.找到问题根源所在,你就能够解决该错误了. 你将看到我认为最基本的解决在C# . ...
- 调试Linq的时候获得相对应的SQL
(query as System.Data.Objects.ObjectQuery).ToTraceString()
- 怎么调试lua性能
怎么调试lua性能 我们的游戏使用的是Cocos2dx-lua 3.9的项目,最近发现我们的游戏.运行比较缓慢.想做一次性能优化了.其实主要分为GPU.CPU的分别优化.GPU部分的优化.网上有很多优 ...
- 微软发布TX(LINQ To Logs And Traces)
微软开源技术公司于发布了Tx,这是一个Apache 2协议的开源项目,可以使用日志/跟踪文件辅助调试,以及创建实时监控和告警系统. 下面是几个引人关注的功能-- 允许在原始事件源上使用LINQ 允许在 ...
- .NET面试题系列[13] - LINQ to Object
.NET面试题系列目录 名言警句 "C# 3.0所有特性的提出都是更好地为LINQ服务的" - Learning Hard LINQ是Language Integrated Que ...
- Code First开发系列之管理数据库创建,填充种子数据以及LINQ操作详解
返回<8天掌握EF的Code First开发>总目录 本篇目录 管理数据库创建 管理数据库连接 管理数据库初始化 填充种子数据 LINQ to Entities详解 什么是LINQ to ...
随机推荐
- 为什么用GPU挖比特币?
http://www.leiphone.com/gpubitcoin.html 呵呵,这么红火的东东,不了解就长不了见识. 转一下两个东东,这挖矿机天天在算什么内容,还有,当前为什么GPU比CPU有优 ...
- 直接将视频文件原码流转换成YUV,输出到屏幕显示
#include "stdafx.h" #define inline _inline#ifndef INT64_C#define INT64_C(c) (c ## LL)#defi ...
- Lua function 函数
Lua支持面向对象,操作符为冒号‘:’.o:foo(x) <==> o.foo(o, x). Lua程序可以调用C语言或者Lua实现的函数.Lua基础库中的所有函数都是用C实现的.但这些细 ...
- Android listView scroll 恢复滚动位置
相信大家尝试过许多方法恢复滚动位置,本人也找了许多方法,唯有这个方法好用,下面把代码贴出来 声明两个变量 private int mPosition; private int lvChildTop; ...
- (转)ASP.NET MVC路由配置
一.命名参数规范+匿名对象 1 routes.MapRoute(name: "Default", 2 url: "{controller}/{action}/{id}&q ...
- HDU --3549
Flow Problem Time Limit: 5000/5000 MS (Java/Others) Memory Limit: 65535/32768 K (Java/Others)Tota ...
- 原生javascript难点总结(1)---面向对象分析以及带来的思考
------*本文默认读者已有面向对象语言(OOP)的基础*------ 我们都知道在面向对象语言有三个基本特征 : 封装 ,继承 ,多态.而js初学者一般会觉得js同其他类C语言一样,有类似于Cl ...
- 创建一个基本的Windows应用程序
以下是包含的头文件 #define WIN32_LEAN_AND_MEAN // 指示编译器不要包含我们并不需要的MFC内容 #include <windows.h> // 包含所有的Wi ...
- git bash【初级入门篇】
最近公司打算使用git代替之前的svn版本控制工具,趁此机会打算好好学学git,这个号称当今世界最牛的分布式版本控制工具. 一.[git和svn的主要区别] 1.去中心化 svn以及微软的TFS均采用 ...
- (经常看看)jdk 设计模式
在JDK(Java Development Kit)类库中,开发人员使用了大量设计模式,正因为如此,我们可以在不修改JDK源码的前提下开发出自己的应用软件,本文列出了部分JDK中的模式应用实例,有兴趣 ...