码迷,mamicode.com
首页 > 其他好文 > 详细

Linq的Bug收集

时间:2015-07-13 12:10:41      阅读:116      评论:0      收藏:0      [点我收藏+]

标签:linq

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,
});




版权声明:本文为博主原创文章,未经博主允许不得转载。

Linq的Bug收集

标签:linq

原文地址:http://blog.csdn.net/mole/article/details/46859923

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!