【问题标题】:LINQ return Mixed Date Between Two Tables With Many-To-One RelationLINQ返回具有多对一关系的两个表之间的混合日期
【发布时间】:2019-04-03 13:56:49
【问题描述】:

我试图返回视图,显示 2 个表之间的混合结果,它们之间存在多对一关系。我知道这是可能的,但我仍处于编程世界的初级阶段,所以我需要一点帮助来做到这一点!

注意:如果用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 表之间存在关系,其中从一章到另一章有很多。它们之间的 Forging 密钥也称为 PostID。

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

【问题讨论】:

  • 你的问题很混乱。您至少需要发布 Post 和 Chapter 的结构,并且您需要解释“混合日期”的含义,甚至可以为两个表格提供一些示例数据以及您想要的结果输出。
  • 你好...我更新了...关于混合内容我的意思是我想从两个表中返回数据

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


【解决方案1】:

如果您想要表 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 对象,包括章节。另一个表的结构相同。

如果您是新手,请首先查看 IRepository、异步方法、await/task.result。

祝你好运!

【讨论】:

  • 谢谢。但是要将它们返回以查看并在那里获取我需要的东西?我的意思是因为我正在使用 VM 我应该在那里定义什么?列表?
  • 你使用的是 MVC 还是 WebApi?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多