使用LINQ多次加入后,从表中获取Sum数据

时间:2017-01-12 16:43:28

标签: c# asp.net-mvc linq join asp.net-web-api

我有EDMX: enter image description here

如果有的话,如何从FreelancerPayment表中获得单个Freelancer的金额总和?如果自由职业者是新手,FreelancerPayment表一直没有金额。我只想要自由职业者列表及其详细信息和总收入。 我试过这个:

var freelancers = (from fl in db.FreelancerLogins
                           join f in db.Freelancers
                           on fl.FreelancerID equals f.FreelancerID
                           select new
                           {
                               FreelancerID = fl.FreelancerID,
                               UserName = fl.UserName,
                               EmailAddress = fl.EmailAddress,
                               EmailConfirmed = fl.EmailConfirmed,
                               Status = fl.Status,
                               LogInTime = fl.LogInTime,
                               LogOutTime = fl.LogOutTime,
                               Picture = f.Picture,
                               Title = f.Title,
                               Name = f.FirstName + " " + f.LastName,
                               Overview = f.Overview,
                               JoiningDate = f.JoiningDate,
                               BirthDay = f.BirthDay,
                               Rate = f.Rate,
                               Location = f.Location,
                               //Earn = (fp.Amount == null ? 0 : fp.Amount)
                               Earn=(
                               from fla in db.Freelancers
                           join apl in db.AppliedJobs
                           on fla.FreelancerID equals apl.FreelancerID into apll
                           from ap in apll.DefaultIfEmpty()

                           join jo in db.JobOffers
                           on ap.AppliedJobID equals jo.AppliedJobID into joo
                           from jobo in joo.DefaultIfEmpty()


                           join c in db.Contracts
                           on jobo.OfferID equals c.OfferID into coo
                           from con in coo.DefaultIfEmpty()

                           join fpay in db.FreelancerPayments
                           on con.ContractID equals fpay.ContractID into fpayy
                           from fp in fpayy.DefaultIfEmpty()

                                   select fp.Amount).Sum()


                           }).AsEnumerable();

        return freelancers.AsEnumerable();

但它返回: enter image description here

所有人的金额相同。我如何为特定的自由职业者设置where子句?

1 个答案:

答案 0 :(得分:2)

您的内部查询应该从连接到外部查询<xsl:analyze-string select="[[[xpath selector for your string]]]" regex="\$\{.+\}"> <xsl:matching-substring> [[[ do your processing of the variable names here ]]] </xsl:matching-substring> </xsl:analyze-string> 的{​​{1}}开始:

AppliedJobs

此外,您不需要在子查询中使用左外连接来计算总和。

最后,你这样做会让它变得更加复杂。你有很好的导航属性,所以Don’t use Linq’s Join. Navigate!并且你没有这样的问题:

Freelancer