LINQ返回具有多对一关系的两个表之间的混合日期

时间:2018-10-30 13:46:57

标签: c# asp.net asp.net-mvc linq asp.net-mvc-4

我试图返回该视图,即两个表之间的混合结果之间存在多对一关系。我知道这是可能的,但是我仍然处于编程世界的起步阶段,因此我需要一些帮助!

注意:如果在LINQ中查询会更好。

这是我的视图模型:

 public class HomeVM
    {

        public List<Post> Comics { set; get; }
        public List<Post> UpdatedComics { set; get; }
        public List<Post> Manga { set; get; }
        public List<Post> UpdatedManga { set; get; }
        public List<Post> Trending { set; get; }
        public IList<Chapter> Chapter{ set; get; }
}

这是发布表:

public Post()
    {
        Chapter = new HashSet<Chapter>();
    }

    public int PostID { get; set; }

    [Display(Name = "Title")]
    [Required]
    [StringLength(150)]
    public string Name { get; set; }

    [AllowHtml]
    [Display(Name = "Description")]
    [Column(TypeName = "text")]
    public string Description { get; set; }

    public virtual ICollection<Chapter> Chapter { get; set; }

这是章节表:

[Table("Chapter")]
public partial class Chapter
{
    public int ChapterID { get; set; }

    [Display(Name = "Chapter Name")]
    [StringLength(150)]
    public string ChapterName { get; set; }

    [Display(Name = "Chapter Slug")]
    [StringLength(150)]
    public string ChapterSlug { get; set; }

    [Required]
    [Display(Name = "Chapter Number")]
    public double ChapterNumber { get; set; }

    [Display(Name = "Post Id")]
    public int PostID { get; set; }

    public virtual Post Post { get; set; }
  }

如您所见,这是我的视图模型,并且在Post Table和Chapter表之间存在一种关系,其中从Chapter一侧到另一侧都有很多关系。它们之间的伪造密钥也称为 PostID

现在我想从控制器返回到我的视图中来自两个表的混合日期,但是我不知道如何编写LINQ查询来做到这一点,因为数据混合了并且我无法在视图中返回混合数据模型..那么我怎么解决这个问题。

1 个答案:

答案 0 :(得分:0)

如果要从表Post中获取所有对象: _repository()是IRepository

using( var repository = _repository() )
{
   var postObjectList = await repository().Get<Post>.Where(_if you need 
   conditions_).Include( a => 
   a.Chapter).ToListAsync();
}

这将为您提供所有具有Where子句中条件的Post对象(包括Chapters)。其他表的结构相同。

首先,请参阅IRepository,异步方法,await / task.result。

祝你好运!