我想从我的数据库构建中执行请求
Table Zipcodes
string Zipcode
string Description
string StateCode
string RegionCode
string CountryCode
Table States
string StateCode
string StateName
Table Region
string RegionCode
string RegionName
Table Country
string CountryCode
string CountryName
所以,我想列出我所有的Zipcodes名称而不是代码。
我的邮政编码表包含8行。 在ZIPCode表中,只有状态代码可以为空。
这是我的要求:
var dset = from s in db.ZIPCODEs
join u in db.COUNTRies on s.COUNTRYCODE equals u.COUNTRYCODE
join v in db.STATES on s.STATECODE equas v.STATECODE
join w in db.REGIONS on s.REGIONCODE equals w.REGIONCODE
select new ZIPCODEListViewModel
{
ID = s.ID,
ZIPCODE1 = s.ZIPCODE1,
DESCRIPTION = s.DESCRIPTION,
STATECODE = s.STATECODE,
CONTRYCODE = s.COUNTRYCODE,
REGIONCODE = s.REGIONCODE,
STATECODE = s.STATENAME,
COUNTRYNAME =u.DESCRIPTION,
STATENAME = v.DESCRIPTION,
REGIONNAME = w.DESCRIPTION
};
返回0行。
如果我只在COUNTRY和REGION上使用join,它不包含空值,我会收到所有行。
我的问题是:如何构建我的请求以返回所有行,并且在Statename中的emply字符串或null是Statecode为null?
感谢您的帮助,对不起英语&&糟糕的linq能力。
罗比
答案 0 :(得分:1)
非常感谢。
帮助我找到解决方案。
var dset = from s in db.ZIPCODEs
join u in db.COUNTRies on s.COUNTRYCODE equals u.COUNTRYCODE into ulist from u in ulist.DefaultIfEmpty()
join w in db.REGIONS on s.REGIONCODE equals w.REGIONCODE into wlist from w in wlist.DefaultIfEmpty()
join v in db.STATES on s.STATECODE equals v.STATECODE into vlist from v in vlist.DefaultIfEmpty()
select new ZIPCODEListViewModel
{
ID = s.ID,
ZIPCODE1 = s.ZIPCODE1,
DESCRIPTION = s.DESCRIPTION,
STATECODE = s.STATECODE,
COUNTRYCODE = s.COUNTRYCODE,
REGIONCODE = s.REGIONCODE,
COUNTRYNAME =u.DESCRIPTION,
STATENAME = v.DESCRIPTION,
REGIONNAME = w.DESCRIPTION
};
在无法通过加入解决的字段中返回所有空白行。
罗比
答案 1 :(得分:0)
您需要使用群组加入而不是加入。组连接工作与SQL中的左连接相同。请尝试以下查询:
var dset = from s in db.ZIPCODEs
join u in db.COUNTRies on s.COUNTRYCODE equals u.COUNTRYCODE
Group Join v In db.STATES On s.STATECODE equas v.STATECODE
Into vlist = Group
From v In vlist.DefaultIfEmpty()
join w in db.REGIONS on s.REGIONCODE equals w.REGIONCODE
select new ZIPCODEListViewModel
{
ID = s.ID,
ZIPCODE1 = s.ZIPCODE1,
DESCRIPTION = s.DESCRIPTION,
STATECODE = s.STATECODE,
CONTRYCODE = s.COUNTRYCODE,
REGIONCODE = s.REGIONCODE,
STATECODE = s.STATENAME,
COUNTRYNAME =u.DESCRIPTION,
STATENAME = v.DESCRIPTION,
REGIONNAME = w.DESCRIPTION
};