用linq连接表

时间:2017-05-10 15:55:05

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

我有4张桌子:

  • 主题
  • RelyTopics
  • TagTopics
  • 标记名。

我想用join和get 2输出执行查询:

  • 加入2个表主题,RelyTopics
  • 并加入2个表TagTopics,T​​agNames

同一视图。

在Controller中我有这段代码:

public ActionResult Index()
{
    var query1 = from to in db.Topics 
                      join rel in db.RelyTopics  on to.IdTopic equals rel.Id
                     select new TopicAndDetails
                     {
                         Topic = to,
                         RelyTopic = rel,
                     };
    var query2 = from tag in db.TagTopics
                join na in db.TagNames on tag.IdTag equals na.IdName
                select new TopicAndDetails
                {
                    TagTopic = tag,
                    NameTag = na,
                };

    var relytopics = new TopicAndDetails(query1, query2) ; //??????

    return View(relytopics.ToList());
}

在模型中有这段代码:

 public partial class TopicAndDetails
{
    public Topic Topic { get; set; }
    public TagName NameTag { get; set; }

    public TagTopic TagTopic { get; set; }
    public RelyTopic RelyTopic { get; set; }
}

1 个答案:

答案 0 :(得分:0)

首先创建导航属性:https://msdn.microsoft.com/en-us/library/jj713564(v=vs.113).aspx,然后就可以执行此操作:

public ActionResult Index()
{
  return db.Topics.Select(t=>new TopicAndDetails {Topic=t})
    .Concat(db.TagTopics.Select(tt=>new TopicAndDetails {TagTopic=tt));
}
public partial class TopicAndDetails
{
    public Topic Topic { get; set; }
    public TagTopic TagTopic { get; set; }
}

您的ViewModel将为IQueryable<TopicAndDetails>IEnumerable<TopicAndDetails>

或者这可能更有意义:

public ActionResult Index()
{
  return new TopicAndDetails {
    Topics = db.Topics.ToList(),
    TagTopics = db.TagTopics.ToList()
  };
}
public partial class TopicAndDetails
{
    public List<Topic> Topics { get; set; }
    public List<TagTopic> TagTopics { get; set; }
}