Linq的Bug收集

来源:互联网 发布:js对话框图片 编辑:程序博客网 时间:2024/06/05 10:43

1、Linq的应用过程中,若是一个对DbContext的对象的引用,则会自动产生一个SQL查询,而且此类对象不能和非SQL类型的对象混用,也就是说下列举例不能被正常执行:

DbSet<CouponSupply> couponSupplies = _context.CouponSupplies;List<SupplyTypeResult> supplyTypes = new List<SupplyTypeResult>();supplyTypes.Add(new SupplyTypeResult{    SupplyTypeId = 2,    SupplyTypeName = "其他投放方式"});IQueryable<CouponSupplyQueryResult> couponSupplyQueryResults = couponSupplies.Join(supplyTypes, p => p.SupplyTypeId, q => q.SupplyTypeId, (p, q) => new CouponSupplyQueryResult{    CouponSupplyId = p.CouponSupplyId,    CouponTypeId = p.CouponTypeId,    CouponTypeName = q.CouponTypeName,    CouponFaceValue = p.CouponFaceValue,    CouponSelfPayMoney = p.CouponSelfPayMoney,});
上述代码中couponSupplies会产生一个SQL查询,而supplyTypes则是非SQL查询,属于静态值类型数据,两者混用时,会报下列错误:

Unable to create a constatnt value of type "VME.Models.SupplyTypeResult". Only primitive types or enumeration types are supported in this context.
解决该问题可以采用下列方式:

1、先通过couponSupplies.ToList()方法获取List对象,确保需要 Join 的两个对象都是非SQL对象。

2、在通过 Linq 的 Join 方法进行级联获取想要的数据。

具体如下:

DbSet<CouponSupply> couponSupplies = _context.CouponSupplies;List<SupplyTypeResult> supplyTypes = new List<SupplyTypeResult>();supplyTypes.Add(new SupplyTypeResult{    SupplyTypeId = 2,    SupplyTypeName = "其他投放方式"});List<CouponSupply> couponSupplys = couponSupplies.ToList();IQueryable<CouponSupplyQueryResult> couponSupplyQueryResults = couponSupplys.Join(supplyTypes, p => p.SupplyTypeId, q => q.SupplyTypeId, (p, q) => new CouponSupplyQueryResult{    CouponSupplyId = p.CouponSupplyId,    CouponTypeId = p.CouponTypeId,    CouponTypeName = q.CouponTypeName,    CouponFaceValue = p.CouponFaceValue,    CouponSelfPayMoney = p.CouponSelfPayMoney,});




0 0
原创粉丝点击