使用Ef核心3.1从Db获取相关数据

时间:2020-05-22 12:58:06

标签: c# entity-framework .net-core linq-to-sql ef-core-3.1

im试图从2个相关表中查询数据(但是EfCore 3.1中没有groupJoin)结果为空,因为相关表中没有item。 我正在使用mvc core 3.1和EF core 3。 代码

    var vmq =
       from req in  _context.Set<QuettaReq>()
               .Where(sd => sd.SiteUserId == _userManager.GetUserId(User) && sd.QuettaClose == false)
                .OrderBy(d => d.ApplicationDate).ThenBy(c => c.Category.CatName)  ///Results should be =1 could be many

       from offers in _context.Set<QuettaOffer>().Where(id => id.QuettaOfferId == req.Id)
           .OrderBy(p => p.OfferPrice) //Results Should be 0 could be many 


       select new {  req,offers,};
        //Results are Empty When it should be ==1 req , 0 offers 

       var combinVm = vmq.Select(t => new ReqOferQestionAnswerVm //ReqOferQestionAnswerVm==Just parameters from 2 tables 
        {
            ReqText = t.req.ReqText,
         //Pram..
        }).ToList();

        return View(combinVm);

我不明白如果2个表的结果为0,那么孔查询为0。

我的班级

 public class QuettaReq
{
    public QuettaReq()
    {
        QuettaOffer = new List<QuettaOffer>();
    }

    [Key] public int Id { get; set; }

    //Pram
    public virtual List<QuettaOffer> QuettaOffer { get; set; }
}

public class QuettaOffer
{
    public QuettaOffer()
    {
    }

    [Key] public   int       QuettaOfferId { get; set; }
    public virtual QuettaReq QuettaReq     { get; set; }
    public         int       QuettaReqId   { get; set; }
}

1 个答案:

答案 0 :(得分:1)

事实上,您是Inner Join而不是Left Join

以这种方式更改它:

var vmq =
   from req in  _context.Set<QuettaReq>()
           .Where(sd => sd.SiteUserId == _userManager.GetUserId(User) && sd.QuettaClose == false)
            .OrderBy(d => d.ApplicationDate).ThenBy(c => c.Category.CatName)  ///Results should be =1 could be many

   join offers in _context.Set<QuettaOffer>().OrderBy(p => p.OfferPrice)
      on req.Id equals offers.QuettaReqId into Joff
   from offers in Joff.DefaultIfEmpty()


   select new {  req,offers,};