![](/img/trans.png)
[英]How to add a entity to collection inside another entity in Entity Framework asp.net mvc
[英]Order by Collection entity property in ASP.NET MVC 3 (entity framework)
我有兩個實體,如:
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public string Lastname { get; set; }
public virtual ICollection<EmployeeEducation> EducationList { get; set; }
}
和
public class EmployeeEducation
{
public int Id { get; set; }
public int EmployeeId { get; set; }
public int Type { get; set; }
[ForeignKey("EmployeeId")]
public virtual Employee Employee { get; set; }
}
我的問題是,如何獲得特定員工和此類員工的教育列表按類型屬性排序?
我努力了:
Employee employee = _work.EmployeeRepository.GetSet()
.SelectMany(e => e.EducationList, (e,d) => new { e, d })
.OrderBy(x => x.d.Type)
.Select(x => x.e)
.FirstOrDefault(e => e.Id == id);
但它似乎並沒有排序。 這樣做的正確方法是什么?
謝謝大家......
取決於你是否使用POCO你應該使用CreateSourceQuery()或Query()在POCO的情況下,例如:
Employee employee = _work.EmployeeRepository.GetSet()
.SelectMany(e => e.EducationList, (e,d) => new { e, d })
.Query()
.OrderBy(x => x.d.Type)
.Select(x => x.e)
.FirstOrDefault(e => e.Id == id);
你做SelectMany()
,但從不使用生成的EducationList
部分,因為你做。選擇.Select(x => xe)
。 但生活難道不簡單嗎? 畢竟,你只有1名員工,為什么不在需要之后立即對其EducationList
排序,如果有必要,請在Include
它之后:
Employee employee = _work.EmployeeRepository.GetSet().Include("EducationList")
.FirstOrDefault(e => e.Id == id);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.