使用linq加入三个表

时间:2012-07-14 09:04:27

标签: linq entity-framework code-first

我有三张桌子:

 public class Description
    {
        public int DescriptionID { get; set; }

        // Attributes 

        public virtual List<Image> Image { get; set; }     

    }

public class Image
    {
        public int ImageID { get; set; }

        // Attributes       

        [Required]
        public int DescriptionID { get; set; }

        [ForeignKey("DescriptionID")]
        public virtual Description Description { get; set; }

        public virtual List<ImageSection> ImageSection { get; set; }
    }



public class ImageSection
    {
        public int ImageSectionID { get; set; }

        // Attributes

        public int? ImageID { get; set; }

        [ForeignKey("ImageID")]
        public virtual Image Image { get; set; }

     }

我有DescriptionID。获得具有该DescriptionID的所有ImageSection的linq是什么?

3 个答案:

答案 0 :(得分:1)

var result = dbContext.Images.Include(i => i.ImageSections)
                 .Where(j => j.DescriptionID == 1)
                 .SelectMany(im => im.ImageSections).ToList(); 

我希望这会有所帮助

答案 1 :(得分:0)

这应该可以解决问题

var descriptions = new List<Description>();

            var descriptionId = 1;

            var result =
                descriptions.Where(d => d.DescriptionID == descriptionId).SelectMany(
                    im => im.Image.SelectMany(ims=> ims.ImageSection));

答案 2 :(得分:0)

考虑到您的问题描述,似乎您不需要加入三个表。由于您已经加入了DescriptionID,因此可以忽略Description表。

试试这个:

var query1 =
    from i in db.Images
    where i.DescriptionID == descriptionID
    join s in db.ImageSections on i.ImageID equals s.ImageID
    select s;

但是,由于您的表定义已包含子集合,因此您可以执行基本SelectMany而无需担心联接本身。

尝试此选择:

var query2 =
    from d in db.Descriptions
    where d.DescriptionID == descriptionID
    from i in d.Image
    from s in i.ImageSection
    select s;