我遇到了关注linq查询的问题。
public class Address
{
public int addressID { get; set; }
public string address { get; set; }
}
public class AdvanceClient
{
public int ClientID { get; set; }
public string Name { get; set; }
public string Mobile { get; set; }
public IEnumerable<Address> Addresses { get; set; }
}
在下面的linq查询中,我想将IEnumerable地址列表分配给Addresses属性。我在tblAdvanceClient和tblAddress表之间有一对多的关系。
IEnumerable<AdvanceClient> addcli = from tbcli in dc.tblAdvanceClients
join tbadd in dc.tblAddresses
on tbcli.AddressID equals tbadd.AddressID
select new AdvanceClient
{
ClientID = tbcli.ClientID,
Company = tbcli.Company,
Fax = tbcli.Fax,
Mobile = tbcli.Mobile,
Name = tbcli.Mobile,
Telephone = tbcli.Telephone,
Addresses = new Address { } // Here i need to get the list of address to each client
};
答案 0 :(得分:3)
而不是
Address = new Address { }
将其更改为
Address = tbcli.Addresses //Since you already have a property in AdvanceClient
所以你的查询是:
IEnumerable<AdvanceClient> addcli =
from tbcli in dc.tblAdvanceClients
join tbadd in dc.tblAddresses
on tbcli.AddressID equals tbadd.AddressID
select new AdvanceClient
{
ClientID = tbcli.ClientID,
Company = tbcli.Company,
Fax = tbcli.Fax,
Mobile = tbcli.Mobile,
Name = tbcli.Mobile,
Telephone = tbcli.Telephone,
Address = tbcli.Addresses
};
答案 1 :(得分:1)
您是否正在使用EntityFramework来检索数据?如果是这样,那么你可以改变你的模型
public class Address
{
public int addressID { get; set; }
public string address { get; set; }
}
public class AdvanceClient
{
public int ClientID { get; set; }
public string Name { get; set; }
public string Mobile { get; set; }
public int AddressId { get; set; }
public virtual Address Addresses { get; set; }
}
EntityFramework将为您加载地址数据。
答案 2 :(得分:1)
这个设计对我来说有点奇怪,有一个地址列表总是只包含一个项目,但如果你肯定需要这个,你可以查询以下内容:
var addcli = from tbcli in dc.tblAdvanceClients
join tbadd in dc.tblAddresses
on tbcli.AddressID equals tbadd.AddressID into addrList
select new AdvanceClient
{
ClientID = tbcli.ClientID,
Company = tbcli.Company,
Fax = tbcli.Fax,
Mobile = tbcli.Mobile,
Name = tbcli.Mobile,
Telephone = tbcli.Telephone,
Addresses = from row in addrList
select new Address
{
addressID = row.AddressID,
address = row.Address
}
};
答案 3 :(得分:0)
我很抱歉,如果我不理解,但我认为它应该如下,因为地址和客户表通过AddressID一对一关联
public class Address
{
public int addressID { get; set; }
public string address { get; set; }
}
public class AdvanceClient
{
public int ClientID { get; set; }
public string Name { get; set; }
public string Mobile { get; set; }
//It can has only one address
public Address Address { get; set; }
}
并查询:
IEnumerable<AdvanceClient> addcli = from tbcli in dc.tblAdvanceClients
join tbadd in dc.tblAddresses
on tbcli.AddressID equals tbadd.AddressID
select new AdvanceClient
{
ClientID = tbcli.ClientID,
Company = tbcli.Company,
Fax = tbcli.Fax,
Mobile = tbcli.Mobile,
Name = tbcli.Mobile,
Telephone = tbcli.Telephone,
//tbadd is the address which you are looking for
Addresses = tbadd;
};