如何获得具有一对多关系的特定列

时间:2016-12-04 20:10:32

标签: c# sql-server linq lambda

我有3张桌子,一对多关系。

我只需要使用SelectMany方法获取特定列。

我只需要获取所选新闻对象的Categories.CategoryName和Comments.CommentDate。

这是我的代码

News news = db.News.Include(w => w.Categories)
                   .Include(w => w.Comments).SingleOrDefault(n => n.NewsId == Id);

以下是我的实体:

新闻实体:

public partial class News
{
    public News()
    {
        this.Categories = new HashSet<Category>();
        this.Comments = new HashSet<Comment>();
    }

    public int NewsId { get; set; }
    public string NewsTitle { get; set; }
    public string NewsBody { get; set; }
    public System.DateTime NewsDate { get; set; }
    public string NewsImagePath { get; set; }

    public virtual ICollection<Category> Categories { get; set; }
    public virtual ICollection<Comment> Comments { get; set; }
}

类别实体:

public partial class Category
{
    public Category()
    {
        this.News = new HashSet<News>();
    }

    public int CategoryId { get; set; }
    public string CategoryName { get; set; }

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

评论实体:

public partial class Comment
{
    public Comment()
    {
        this.News = new HashSet<News>();
    }

    public int CommentId { get; set; }
    public string CommentBody { get; set; }
    public Nullable<System.DateTime> CommentDate { get; set; }

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

2 个答案:

答案 0 :(得分:1)

这个LINQ查询应该处理它:

var query =
    from news in db.News
    where news.Id == Id
    let categoryNames =
        from category in news.Categories
        select category.Name
    let commentDates =
        from comment in news.Comments
        select comment.CommentDate
    select new {
        CategoryNames = categoryNames.ToList(),
        CommentDates = commentDates.ToList()
    };

该查询未使用SelectMany,但这对您没有帮助,因为那时您将无法按新闻项对您的类别和评论进行分组。由于类别和评论没有直接关联,您需要两个SelectMany,然后您需要交叉加入结果。那显然不是你想要的。

答案 1 :(得分:0)

也许尝试使用以下内容?

var categoryNames = news.Categories.Select(c=>c.CategoryName);
var commentDates = news.Comments.Select(c=>c.CommentDate);

请注意,SelectMany用于展平列表。例如,假设您收集了符合特定搜索条件的新闻,然后使用SelectMany收集所有Categories /这些新闻的Comments列在一个单一的列表中。