C#从实体框架中将插入订单放入列表中

时间:2017-06-13 16:15:56

标签: c# asp.net asp.net-mvc entity-framework

我很惊讶地发现,当从实体框架选择中实例化时,我将插入订单问题放入C#列表。

我正在创建多个包含List<int>个键的dtos,但每个dto对象的插入顺序是随机的。这是最奇怪的事情。我认为保存了C#列表中的插入顺序,所以我试图弄清楚订单的确定位置。

服务器代码:

var locations = Context.Location
        .Where(x => x.fk_LocationId == id)
        .Include(t => t.DoctorLocations);

Region.Locations = locations
        .SelectMany(x => x.DoctorLocations)
        .Where(y => y.fk_LocationId == id)
        .Select(x =>
            new SortableItem
            {
                Keys = new List<int> { x.fk_doctorId, x.fk_locationId },
                Type = "Practice",
                Priority = x.Priority ?? 0,
            })
        .OrderBy(x => x.Priority)
        .ToList();

查看:

@for (var i = 0; i < Model.DoctorLocations.Count(); i++)
{
    @Html.ActionLink("Remove", "Delete", "DoctorLocation" new { doctorId= Model.Locations[i].Keys[0], locationId= Model.Locations[i].Keys[1], }, null)
}

更新Per @PaulAbbot

我删除了SelectMany但获得了相同的结果。我还创建了更多的dto对象,以便在它们交替时查找模式。我没有看到一个,但它们与从服务器返回的方式一致。

Region.Locations = Context.DoctorLocations
        .Where(y => (y.fk_doctorId == doctorId) &&
            locations.Select(x => x.locationId).Contains(y.fk_locationId))
        .Where(y => y.fk_doctorId == doctorid)
        .Select(x =>
            new SortableItem {
                Keys = new List<int> { x.fk_doctorId, x.fk_locationId }
            })
        .OrderBy(x => x.Priority)
        .ToList();

1 个答案:

答案 0 :(得分:2)

看起来EF6处理投影中存在包含new List<int> { val1, val2, ...}等构造的错误。虽然它不生成NotSupportedException,但正确实现结果所需的生成的SQL ORDER BY子句是错误的(使用常量而不是索引选择器表达式)。

如果您不需要IQueryable<T>结果,我会建议通常的双投影解决方法 - 在LINQ to Entities查询中使用普通的匿名类型投影,然后在最后切换到LINQ to Objects并执行所需的投影:

var result = locations
    .SelectMany(x => x.DoctorLocations)
    .Where(y => y.fk_LocationId == id)
    .Select(x => new
    {
        K1 = x.fk_doctorId, K2 = x.fk_locationId,
        Type = "Practice",
        Priority = x.Priority ?? 0,
    })
    .OrderBy(x => x.Priority)
    .AsEnumerable() // switch to L2O
    .Select(x => new SortableItem
    {
        Keys = new List<int> { x.K1, x.K2 },
        Type = x.Type,
        Priority = x.Priority,
    })
    .ToList();

我知道,很烦人,但至少按预期工作:)