看起来我遇到了嵌套的Linq Query。我有4个表,我想加入。基本上,期刊有一个收件人和多个读者。我想用它的收件人及其所有读者来展示期刊。这是EF查询
var myJournals = (
from s in db.Journals
where !s.Blacklist
join recToJournals in db.RecipientsToJournals on s.JournalID equals recToJournals.JournalID
join recipients in db.Recipients on recToJournals.RecipientID equals recipients.RecipientID
join reaToJournals in db.ReadersToJournals on s.JournalID equals reaToJournals.JournalID
join readers in db.Readers on reaToJournals.ReaderID equals readers.ReaderID
select new AnalysisViewModel
{
JournalID = s.JournalID,
Title = s.Title,
RecipientName = recipients.FullName,
ReaderList = readers.FullName.ToList()
});
return View(myJournals);
这是ViewModel:
public class AnalysisViewModel
{
public int JournalID { get; set; }
public string Title { get; set; }
public List<Char> ReaderList { get; set; }
public string ReaderName { get; set; }
public string RecipientName { get; set; }
}
在这里,我将获得例外System.NotSupportedException: The method 'ToList' is not supported when called on an instance of type 'String'.
如果我使用ReaderName = readers.FullName
它有效,但我得到一个包含多个期刊及其读者的列表。
如何只显示一个包含收件人的日记和所有读者?
答案 0 :(得分:1)
这没有意义。你为什么要在字符串上调用ToList
?为什么你甚至想要List<char>
?更改模型,使其类型为string
,然后移除ToString
在你的linq声明中改变1 -
ReaderList = readers.FullName // remove .ToList
在模型中更改2 -
public string ReaderList { get; set; }
虽然技术上没有错,但最佳做法是使用后缀List命名string类型的属性(或该mater的任何非集合类型)。更合适的名称是ReaderName
。
答案 1 :(得分:0)
首先更改您的ViewModel
knock knock!
您需要 public class AnalysisViewModel
{
public int JournalID { get; set; }
public string Title { get; set; }
public string RecipientFullName { get; set; }
public List<string> ReadersFullNames { get; set; }
}
GroupBy