【发布时间】:2017-02-06 20:42:02
【问题描述】:
我有 2 个表,每个表与之间的表具有一对多关系,并且表之间的表具有 2 个其他表的 id
dbo.Posts dbo.Posts_Categories dbo.Categories
-ID -ID -ID
-Title -PostID -Name
-CategoryID
我期望的结果是:
Title = post1 Categories = web,mobile,desktop
Title = post2 Categories = app,game
...
我知道如何在 sql 中使用 Stuff 函数和 For Xml Path 进行查询,但我不知道如何在实体框架中执行此操作!
任何关于如何以这种方式工作的建议或书籍都可能有所帮助!
编辑:添加了 EF 类:
public class Post : ReportingBase {
public Post() { }
[Required, MaxLength(500)]
public string Title { get; set; }
[Required, MaxLength(500)]
public string Address { get; set; }
[Required]
public string Body { get; set; }
[Required, MaxLength(500)]
public string Tags { get; set; }
[Required]
public int Visit { get; set; }
public virtual ICollection<Post_Category> Posts_Categories { get; set; }
public virtual ICollection<Post_AttachedFile> Posts_AttachedFiles { get; set; }
[ForeignKey("Image")]
public virtual int? ImageID { get; set; }
public virtual Image Image { get; set; }
}
public class Post_Category {
public Post_Category() { }
[Key, Column(Order = 0)]
public int PostID { get; set; }
[Key, Column(Order = 1)]
public int CategoryID { get; set; }
public virtual Post Post { get; set; }
public virtual Category Category { get; set; }
}
public class Category : EntityBase {
public Category() { }
[Required, MaxLength(50)]
public string Name { get; set; }
[Required, MaxLength(150)]
public string Address { get; set; }
public int? ParentID { get; set; }
public virtual ICollection<Post_Category> Posts_Categories { get; set; }
}
提前谢谢你
编辑:根据@IvanStoev 的回答,我做了以下操作:
List<P> p = context.Posts.Select(post => new {
Title = post.Title,
Categories = post.Posts_Categories.Select(pc => pc.Category.Name).ToList()
}).ToList();
并创建了一个名为 P 的类:
public class P {
public string Title { get; set; }
public List<string> Categories { get; set; }
}
但它不能正常工作,问题是如何返回结果。
【问题讨论】:
-
好吧,为了帮助进行 EF 查询,我们需要 EF 模型(类、流式配置等)而不是 db 表。
-
我添加了实体@IvanStoev
-
您可以删除所有那些空的构造函数 - 只会使您的代码变得模糊。另外,在定义一对多关系时,建议使用
ICollection<Type>而不是List<Type>。
标签: c# entity-framework linq join many-to-many