簡體   English   中英

如何在LINQ中將Entity類型的自定義屬性設置為Entities查詢,並且仍然返回IQueryable <T> ?

[英]How can I set custom property of an Entity type in LINQ to Entities query and still return a IQueryable<T>?

我有一個EF4模型,其中有與任務實體(ChildTasks)具有一對多關系的產品實體。 我必須根據某些用戶條件從數據庫獲取一些項目。 該項目有一個名為EstimatedProgress的自定義屬性(不與任何列關聯),在這里我必須存儲有關項目的其他信息-每個子任務的計算加權平均進度。 問題是,最終我不能返回IEnumerable <Project>而返回IQueryable <Project> 下面的代碼演示了我想要實現的目標(我知道它不會編譯)。

var q = from p in ObjectContext.ProjectSet.Include("ProjectBase") 
        where p.ProjectBase.IsTemplate == false 
        from ct in p.ProjectBase.ChildTasks
        where ct.Progress != null
           && ct.EstimatedTime != null
        group ct by ct.prjProjectBase.Project into g
        select new {
            Project = g.Key,
            EstimatedProgress = g.Sum(oo => oo.Progress.Value * oo.EstimatedTime.Value) 
                              / g.Sum(oo => oo.EstimatedTime.Value),
        };

var sortedQ = q.OrderByDescending(o => o.Project.ProjectBase.Status)
          .ThenBy(o => o.Project.ProjectBase.Name);

// this is where I want to return IQueryable<Project> 
// where each project has set custom property EstimatedProgress
return sortedQ.Select(o =>
{
    o.Project.EstimatedTime = o.EstimatedProgress;
    return o.Project;
});

問題是:是否可以用EF4 linq查詢做類似的事情,或者您中的某些人有解決方法;)提前謝謝。

您可以聲明簡單的包裝器類

public class ProductWithEstimation 
{ 
    public Product Product { get; set; } 
    public double? EstimatedTime { get; set; }
}

並返回IQueryable<ProductWithEstimation>

最簡單的選擇是將邏輯移到定制屬性getter中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM