假设我有一个非常简单的数据库图:
以及对它的看法:
create view vTraining
as
select t.Id as TrainingId,t.[Status] ,
t.[User], t.Title,t.Organisation,t.[Month],t.[Year],
s.Id as SubjectId, s.Name as SubjectName,
c.Text as Comment
from Training t
join Subject s on s.Training = t.Id
join Comment c on c.Training = t.Id
带有样本数据:
如您所见,这是一个包含三个主题的单一培训。我想通过 linq to sql 将此结果映射到此结构:
public class ViewModel
{
public string Comment { set; get; }
public List<Item> Trainings { set; get; }
}
public class Item
{
public int TrainingId { set; get; }
public int User { set; get; }
public int Status { set; get; }
public string Title { set; get; }
public string Organisation { set; get; }
public int? Month { set; get; }
public int Year { set; get; }
public List<KeyValuePair<int, string>> Subjects { set; get; }
}
这是我创建的查询:
var data = (from training in dc.vTrainings
group training by new
{
training.TrainingId,
training.Status,
training.Month,
training.Organisation,
training.Title
}
into g
select new ViewModel()
{
Comment = g.Select(x =>
x.Comment).First(),
Trainings = g.Select(
x => new Item()
{
Month = x.Month,
Organisation = x.Organisation,
Title = x.Title,
Year = x.Year,
Subjects = g.Select(
z => new KeyValuePair<int, string>(z.SubjectId, z.SubjectName)).ToList()
}).ToList()
})//.GroupBy(x => x.Trainings).Select(x => x.Key)
.ToList();
不幸的是,我得到的结果不是我想要的:
ViewModel 对象只创建可以的对象,但对于每个单独的主题,都会创建新的项目(应该是一个)。Subjets 列表已正确创建。我试图创建第二组,以及其他一些东西,但这是我现在能得到的最好结果。如何编写此查询以获取一个 ViewModel 对象,该对象具有一个 Item 对象和三个主题?