1
我使用EF4.1代码首先,EF LINQ查询收集与渴望加载的子收集
我试图创建一个查询返回的集合与渴望加载的子收集。 双方必须通过位置和IsActive ==真
这些类映射进行排序。
public class Type
{
public int Id { get; set; }
public int AreaId { get; set; }
public bool IsActive { get; set; }
public int Position { get; set; }
.......
public virtual IList<Category> Categories { get; set; }
}
public class Category
{
public int Id { get; set; }
public int TypeId { get; set; }
public bool IsActive { get; set; }
public int Position { get; set; }
.......
public virtual Type Type { get; set; }
}
的DTO:
public class TypeDTO
{
public string Name { get; set; }
public string UniqueName { get; set; }
public virtual IList<CategoryDTO> Categories { get; set; }
}
public class CategoryDTO
{
public string Name { get; set; }
public string UniqueName { get; set; }
public virtual TypeDTO Type { get; set; }
}
什么我有:
随着DTO:
var result = _db.Types
.Where(x => x.IsActive == true)
.Where(x => x.AreaId== areaId)
.Select(x => new TypeDTO()
{
Name = x.Name,
UniqueName = x.UniqueName,
Categories = x.Categories.Where(c => c.IsActive == true)
.OrderBy(c => c.Position)
.Select(c => new CategoryDTO()
{
Name = c.Name,
UniqueName = c.UniqueName
})
.ToList()
})
.ToList();
此抛出:
LINQ到恩tities无法识别方法 'System.Collections.Generic.List
1[...CategoryDTO] ToList[...CategoryDTO](System.Collections.Generic.IEnumerable
1 [... CategoryDTO])' 方法,并且此方法无法转换为存储表达式。
没有DTO:
var result2 = _db.Categories
.Where(x => x.IsActive == true)
.OrderBy(x => x.Position)
.Select(x => x.Type)
.Distinct()
.Where(x => x.IsActive == true && x.AreaId== areaId)
.OrderBy(x => x.Position)
.ToList();
它运行没有错误,但并没有给出正确的结果,并没有订购孩子收集
其他不成功的做法:
var result = _db.Types
.Where(t => t.IsActive == true)
.Where(t => t.SiteId == siteId)
.Include(t => t.Categories
.Where(c=>c.IsActive == true)
.OrderBy(c=>c.Position))
.OrderBy(t => t.Position)
.ToList();
我错过了什么?
谢谢。
编辑 最终的解决方案:
public class TypeDTO
{
public Type Type { get; set; }
public IEnumerable<Category> Categories { get; set; }
}
var result = _db.Types
.Where(x => x.IsActive == true)
.Where(x => x.AreaId== areaId)
.OrderBy(x=>x.Position)
.Select(x => new TypeDTO()
{
Type = x,
Categories = x.Categories.Where(c => c.IsActive == true).OrderBy(c => c.Position)
})
.ToList();
谢谢您的回答,但** **类型必须是一个列表不是条目 – jani
谢谢,编辑版本的作品。我需要更新DTO类:** public class TypeDTO { public Type Type {get;组; } public IEnumerable类别{get;组; } } ** –
jani