Linq2Sql Many:Many question, How would you do this?

可紊 提交于 2019-12-20 10:13:21

问题


I know many:many isn't supported in Linq2Sql but I am working on a workaround

I am working with my little SO clone and I have a table with Questions and a table with Tags and a linking table QuestionTag so I have a classic many:many relationship between Questions and Tags.

To display the list of Questions on the front page I have this class I want to fill up from a Linq2Sql query

public class ListQuestion
{
   public int QuestionID { get; set; }
   public string Title{ get; set; }
   public IEnumerable<Tag> Tags { get; set; }
}


public IEnumerable<ListQuestion> GetQuestions()
{
   from q in Questions
   .................
   select new ListQuestion{ ... }
}

The problem is how should I fill up the Tag collection. I found out this isn't possible to do in 1 single query so I have divided this into 2 queries, 1 to get the questions and 1 to get the tags and later try to join them. I know many:many is supported in Entity framework so how do they do it? How would you do this? Any alternative approach? The query should of course be efficient.


回答1:


This may work for your case;

from q in Questions
select new ListQuestion 
{ 
  Tags = q.QuestionTags.Select(qt => qt.Tag),
  QuestionId = q.ID,
  Title = q.Title
}


来源:https://stackoverflow.com/questions/368854/linq2sql-manymany-question-how-would-you-do-this

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!