【发布时间】:2016-11-03 13:56:51
【问题描述】:
我有两张桌子
Person
__________
PersonID
PersonName
DOB
Status
Notes
__________
NoteID
PersonID
NoteText
Comments
LineNo
这里是一些示例内容
PersonID PersonName DOB Status
1 Mark Jacobs 07/07/1961 Active
和
NoteID PersonID NoteText LineNo
123 1 Line 1 1
234 1 Line 2 2
236 1 Line 3 3
因此,作为最终结果,我希望 Linq 查询显示类似的内容
PersonID PersonName DOB Note
1 Mark Jacobs 07/07/1961 Line 1
Line 2
Line 3
到目前为止,我发现的所有示例都只有一个表,因此我尝试从仅对 Notes 表进行分组开始,如下所示:
var result = (from n in db.Notes
group n.NoteText by n.PersonID into g
select new NoteGrp {
PersonID = g.Key,
Notes = g.ToList().ToString()
}).AsEnumerable();
在函数中是这样的:
public IEnumerable<NoteGrp> GetNotes()
{
using (MyContext db = new MyContext())
{
var result = (from n in db.Notes
group n.NoteText by n.PersonID into g
select new NoteGrp { PersonID = g.Key, Note = g.ToList().ToString() }).AsEnumerable();
return result;
}
}
它编译得很好并且会出错,直到它得到返回结果。如果我在监视窗口中查看结果对象并将其展开以显示结果,我会看到 The entity or complex type 'NoteGrp' cannot be constructed in a LINQ to Entities query 内部异常。
但是如果我让它运行,那么在浏览器中我会得到以下信息:The 'ObjectContent1' type failed to serialize response body for content type 'text/html;`
附: NoteGrp 是我创建的一个类,它只包含 2 个成员:作为 int 的 PersonID 和作为字符串的 Notes
public class NoteGrp
{
[Key]
public int PersonID { get; set; }
public string Notes { get; set; }
}
我也尝试过使用
var result = db.Notes.GroupBy(n => new { n.PersonID }).Select(g => new NoteGrp{PersonID= g.Key.personID, Notes = string.Join(",", g.Select(x => x.NoteText)) }).ToList();
并得到了无法构造复杂类型实体的相同错误。我可以使用匿名类型:
var result = db.Notes.GroupBy(n => new { n.PersonID }).Select(g => new {PersonID= g.Key.personID, Notes = string.Join(",", g.Select(x => x.NoteText)) }).ToList();
但是我不确定我的函数应该有什么返回类型...
【问题讨论】:
-
请显示
NoteGrp的定义 -
添加了 NoteGrp
-
人物和笔记是否通过主键和外键关系相关?如果是这样,它非常简单: db.Persons.Include(p => p.Notes).Select(p => new NoteGrp{ });我没有检查语法。但这应该会给你一些想法。
-
你为什么不在 Person 类上放一组 Notes 让 EF 为你填充呢?
标签: c# entity-framework linq