我有4张桌子:
我想用join和get 2输出执行查询:
同一视图。
在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; }
}
答案 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; }
}