我是ASP.NET和MVC的新手,所以请耐心等待。我有两个模型:
public class Change
{
public int ID { get; set; }
public string Title { get; set; }
// more fields
public virtual ICollection<ChangeHistory> ChangeHistory { get; set; }
}
和
public class ChangeHistory
{
public int ID { get; set; }
public int ChangeID { get; set; }
public DateTime Date {get; set; }
public Status Status {get; set; }
}
目前,我的更改视图只列出表格中的所有更改及其详细信息(ID,标题等)。我想要的是从详细信息表中添加几个列,例如Inititiaton Date(给定更改的第一个ChangeHistory项的日期)和Current Status&amp;日期(均来自给定变更的最后一个ChangeHistory项目。)
我首先创建了一个新的ViewModel:
public class ChangeViewModel
{
// Take these details from the change record
public int ID { get; set; }
public string Title { get; set; }
public string Description { get; set; }
// Take these details from the first change history record
public DateTime InitiationDate { get; set; }
// Take these details from the latest change history record
public DateTime StatusDate { get; set; }
public Status CurrentStatus { get; set; }
}
在我的ChangesController中,在我缺乏经验使我陷入困境之前,我已经找到了启动日期:
var ChangeWithStatus = from c in db.Changes
from h in db.ChangeHistories
where c.ID == h.ChangeID && h.Date ==
(
from h2 in db.ChangeHistories
where c.ID == h2.ChangeID
select h2.Date
).Min()
select new ChangeViewModel
{
// Change details
ID = c.ID,
Title = c.Title,
Description = c.Description,
// Initiation details
InitiationDate = h.Date,
Initiator = h.User,
// Status details
StatusDate = h.Date,
CurrentStatus = h.Status,
User = h.User
};
我想知道解决方案是使用自己的linq语句检索每个ChangeHistory记录,然后将它们与第三个组合。任何人都可以帮我解决这个问题吗?提前谢谢。
答案 0 :(得分:2)
这应该有效:
var changeViewModels = (from change in db.Changes
let lastChangeHistory = change.ChangeHistory.OrderByDescending(changeHistory => changeHistory.Date).FirstOrDefault()
let firstChangeHistory = change.ChangeHistory.OrderBy(changeHistory => changeHistory.Date).FirstOrDefault()
select new ChangeViewModel
{
ID = change.ID,
Title = change.Title,
Description = change.Description,
InitiationDate = firstChangeHistory.Date,
StatusDate = lastChangeHistory.Date,
CurrentStatus = lastChangeHistory.Status,
}).ToList();
使用let clause这一行:
let lastChangeHistory = change.ChangeHistory.OrderByDescending(changeHistory => changeHistory.Date).FirstOrDefault()
将为您提供每次更改的最后更改历史记录。 这一行:
let firstChangeHistory = change.ChangeHistory.OrderBy(changeHistory => changeHistory.Date).FirstOrDefault()
会给你第一个。
现在您拥有了所需的所有数据,您可以将其选择到ChangeViewModel中。