我想通过合并来自ViewModel中两个表的数据来绑定下拉列表。你能否澄清一下我该怎么做?例如,我想在一行中的2个表中显示4个字段,如下所示:
MeetingName / MeetingCityIdA的名称 / MeetingCityIdB的名称 / MeetingDate
以下是我使用的实体:
会议
public int MeetingID { get; set; }
public string MeetingName { get; set; }
public DateTime MeetingDate { get; set; }
public int? MeetingCityIdA { get; set; }
public int? MeetingCityIdB { get; set; }
public int? MeetingCityIdC { get; set; }
的城市:
public int CityID { get; set; }
public string CityName { get; set; }
的视图模型:
public class ViewModel
{
public Applicant Applicant { get; set; }
public IEnumerable<Applicant> Applicants { get; set; }
public IEnumerable<Meeting> Meetings { get; set; }
public IEnumerable<City> Cities { get; set; }
}
的型号:
答案 0 :(得分:1)
您可以使用下一个linq查询:
var list = Meetings.GroupJoin(Cities, m => m.MeetingCityIdA, c => c.CityID, (m, c) => new {m, cA = c.DefaultIfEmpty()})
.SelectMany(z => z.cA.Select(cA => new { m = z.m, cA })
.GroupJoin(Cities, m => m.m.MeetingCityIdB, c => c.CityID, (m, c) => new {m.m, m.cA, cB = c.DefaultIfEmpty()})
.SelectMany(z => z.cB.Select(cB => new { m = z.m, cA= z.cA, cB })
.GroupJoin(Cities, m => m.m.MeetingCityIdC, c => c.CityID, (m, c) => new {m.m, m.cA, m.cB, cC = c.DefaultIfEmpty()})
.SelectMany(z => z.cC.Select(cC => new { m = z.m, cA= z.cA, cB = z.cB, cC })
.Select(
m =>
new
{
m.m.MeetingName,
NameofMeetingCityIdA = m.cA!=null?m.cA.CityName:null,
NameofMeetingCityIdB = m.cB!=null?m.cB.CityName:null,
NameofMeetingCityIdC = m.cC!=null?m.cC.CityName:null,
m.m.MeetingDate
});
它在MeetingCityIdA上加入与Cities的会议,然后将结果连接到MeetingCityIdB上的Cities,然后选择你想要的内容。
但是,如果您将实体的导航属性用于而不是使用来自linq的Join语句,那将是正确的。
答案 1 :(得分:0)
@Kirill Bestemyanov的更新和工作答案:
var list = repository.Meetings
.GroupJoin(repository.Cities, m => m.MeetingCityIdA, c => c.CityID, (m, c) => new {m, cA = c.DefaultIfEmpty()})
.SelectMany(z => z.cA.Select(cA => new { m = z.m, cA }))
.GroupJoin(repository.Cities, m => m.m.MeetingCityIdB, c => c.CityID, (m, c) => new {m.m, m.cA, cB = c.DefaultIfEmpty()})
.SelectMany(w => w.cB.Select(cB => new { m = w.m, cA= w.cA, cB }))
.GroupJoin(repository.Cities, m => m.m.MeetingCityIdC, c => c.CityID, (m, c) => new {m.m, m.cA, m.cB, cC = c.DefaultIfEmpty()})
.SelectMany(t => t.cC.Select(cC => new { m = t.m, cA= t.cA, cB = t.cB, cC }))
.Select(
m =>
new
{
m.m.MeetingName,
NameofMeetingCityIdA = m.cA!=null?m.cA.CityName:null,
NameofMeetingCityIdB = m.cB!=null?m.cB.CityName:null,
NameofMeetingCityIdC = m.cC!=null?m.cC.CityName:null,
m.m.MeetingDate
});