是否可以在.Select
查询的LINQ to Entities
部分中设置子查询,以便在我的视图模型中填充List<string>
?我发现Use Linq To Entities subquery within Select clause to fetch a field value但是当我尝试这样做时,我收到错误:
NotImplementedException:Microsoft.Data.Entity.Query.ResultOperators.Internal.QueryAnnotationResultOperator
这可能与Entity Framework 7和ASP.Net 5 MVC 6有关吗?
var model = _DbContext.ReleaseVersions
.OrderByDescending(rv => rv.DateReleased)
.Select(rv => new ReleaseNotesVM()
{
ID = rv.ID,
CurrentVersion = string.Concat(rv.Major, '.', rv.Minor, '.', rv.Patch),
ReleaseNotes = _DbContext.ReleaseNotes
.Where(rn => rn.ReleaseVersionID == rv.ID)
.Include(rn => rn.ReleaseVersion)
.Select(rn => rn.Note)
.ToList()
}).FirstOrDefault();
ViewModel正在填充:
public class ReleaseNotesVM
{
public byte ID { get; set; }
public string CurrentVersion { get; set; }
public DateTime CurrentVersionReleaseDate { get; set; }
public IEnumerable<SelectListItem> VersionList { get; set; }
public byte SelectedVersionID { get; set; }
public ICollection<string> ReleaseNotes { get; set; }
}
的DataModel:
public class ReleaseVersion
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public byte ID { get; set; }
public DateTime DateReleased { get; set; }
public byte Major { get; set; }
public byte Minor { get; set; }
public byte Patch { get; set; }
public virtual ICollection<ReleaseNote> ReleaseNotes { get; set; }
}
public class ReleaseNote
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }
public string Note { get; set; }
public byte ReleaseVersionID { get; set; }
[ForeignKey("ReleaseVersionID")]
public ReleaseVersion ReleaseVersion { get; set; }
}
答案 0 :(得分:1)
如果我假设正确,您必须在ReleaseVersions
和ReleaseNotes
之间建立一对多的关系,这意味着ReleaseVersion
类中应该有一个导航属性ReleaseNotes
的集合,使您可以像这样重写代码:
var model = _DbContext.ReleaseVersions
.Include(rv => rv.ReleaseNotes)
.OrderByDescending(rv => rv.DateReleased)
.Select(rv => new ReleaseNotesVM
{
ID = rv.ID,
CurrentVersion = string.Concat(rv.Major, '.', rv.Minor, '.', rv.Patch),
ReleaseNotes = rv.ReleaseNotes.Select(rn => rn.Note).ToList()
}).FirstOrDefault();
<强>更新强>
在List<string> ReleaseNotes
中使用ICollection<string>
代替ReleaseNotesVM
。