在LINQ中写左连接查询

时间:2013-05-05 05:24:01

标签: c# asp.net-mvc linq

select a.stakebuyinid , a.StakeBuyInValue  from StakeBuyInByStakeCategories  AS b 
left join StakeBuyIns AS a on b.stakebuyinid = a.stakebuyinid 
where b.GametypeId = 1 and b.StakeCategoryID = 3 and a.Currencyid = 1

上面是我想在LINQ中编写的简单SQL查询

我正在使用以下LINQ查询但是引发错误: - “转换为值类型'Int32'失败,因为具体化值为null。结果类型的泛型参数或查询必须使用可空类型。”

var query = (from v in db.StakeBuyInByStakeCategories.Where(x => x.GameTypeId == gametypeid && x.StakeCategoryId == stakecategoryid)
                        join u in db.StakeBuyIns.Where(y => y.CurrencyId == currencyid)
                               on v.StakeBuyInId equals u.StakeBuyInId into Temp
                           from vus in Temp.DefaultIfEmpty()
                       select new {
                           vus.StakeBuyInId,
                           vus.StakeBuyInValue )

2 个答案:

答案 0 :(得分:1)

假设
StakeBuyInByStakeCategoriesList as IEnumerable<StakeBuyInByStakeCategories>StakeBuyInsList as IEnumerable<StakeBuyIns>

(from b in StakeBuyInByStakeCategoriesList 
 from a in StakeBuyInsList    
.Where(b.stakebuyinid equals a.stakebuyinid)
.DefaultIfEmpty()    
.Where( b.GametypeId == 1 and b.StakeCategoryID == 3 and a.Currencyid == 1)    
select new {Stakebuyinid=a.stakebuyinid, StakeBuyInValue=a.StakeBuyInValue}

答案 1 :(得分:0)

模型中的int应该是int?,因为可以使用可空的返回值。