2014-03-05 78 views
1

我有一个MVC应用程序,在其中我试图通过连接它们来从多个表中拉出一条记录。在应用程序中,我有一张动物表,一张出生表和一张购买表。每只动物在动物表中都有一个记录,但只有购买到农场的动物才会在购买表中有记录,同样只有在农场出生的动物才会在出生记录中记录。因此,无论出生表或购表人总是会返回一个空的查询我有以下:多个外层Linq连接

CowDetailVM animal = (from animals in db.Animals 
           join breed in db.Breeds on animals.AnimalBreed equals breed.id 
           join birth in db.Births on animals.TagNo equals birth.TagNo 
           join purchase in db.Purchases on animals.TagNo equals purchase.TagNo 
           where animals.TagNo == id && animals.UserId == WebSecurity.CurrentUserId 
           orderby animals.DateAdded descending 

           select new CowDetailVM 
           { 
            TagNo = animals.TagNo, 
            Sex = animals.Sex, 
            AnimalBreed = breed.Breed1, 
            DOB = animals.DOB, 
            OwnershipStatus = animals.OwnershipStatus, 
            BornOnFarm = animals.BornOnFarm, 

            /*DateBought = purchase.DateBought, 
            BoughtFrom = purchase.BoughtFrom, 
            Price = purchase.Price, 
            Location = purchase.Location, 

            MotherTagNo = birth.MotherTagNo, 
            SireTagNo = birth.SireTagNo, 
            Difficult = birth.Difficult*/ 

           }).FirstOrDefault(); 

我如何选择数据,即使一个表中返回一个空。或者有更好的方法来做到这一点?

谢谢

回答

1

你几乎明白了。您的查询翻译成INNER JOIN s。要在birthpurchase表上执行LEFT JOIN,您可以执行以下操作。

CowDetailVM animal = (from animals in db.Animals 
         join breed in db.Breeds on animals.AnimalBreed equals breed.id 
         join birth in db.Births on animals.TagNo equals birth.TagNo into j0 
         from birth in j0.DefaultIfEmpty() 
         join purchase in db.Purchases on animals.TagNo equals purchase.TagNo into j1 
         from purchase in j1.DefaultIfEmpty() 
         where animals.TagNo == id && animals.UserId == WebSecurity.CurrentUserId 
         orderby animals.DateAdded descending 

         select new CowDetailVM 
         { 
          TagNo = animals.TagNo, 
          Sex = animals.Sex, 
          AnimalBreed = breed.Breed1, 
          DOB = animals.DOB, 
          OwnershipStatus = animals.OwnershipStatus, 
          BornOnFarm = animals.BornOnFarm, 

          /*DateBought = purchase.DateBought, 
          BoughtFrom = purchase.BoughtFrom, 
          Price = purchase.Price, 
          Location = purchase.Location, 

          MotherTagNo = birth.MotherTagNo, 
          SireTagNo = birth.SireTagNo, 
          Difficult = birth.Difficult*/ 

         }).FirstOrDefault(); 
+0

感谢您的帮助。工作完美 – user2437588