我可以在LINQ to Entities的SELECT中执行子查询来填充模型中的List吗?

时间:2016-01-18 20:46:33

标签: linq entity-framework-core

是否可以在.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; }
}

1 个答案:

答案 0 :(得分:1)

如果我假设正确,您必须在ReleaseVersionsReleaseNotes之间建立一对多的关系,这意味着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