Linq的Bug收集

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值