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