c# - Linq many to many selection -
i have 2 tables many many relationship, in post-detail page want show related posts, related posts post have @ least category of current post. how can select related posts of current post? tried code , it's not want:
[childactiononly] public partialviewresult getrelatedpost(int id) { var relatedposts = _db.posts.select(x => new { x.id, x.title, x.slug, x.image, x.isactive,x.posttype,x.postcategories }) .where(x => x.isactive && x.id != id && x.postcategories.intersect(_db.postcategories).any()) .orderbydescending(x => x.id).take(20) .tolist(); }
update: solve problem code:
var posts = _db.posts.select(x => new { x.id, x.title, x.slug, x.image, x.isactive,x.posttype,x.postcategories }) .where(x => x.isactive && x.id != id && x.postcategories.intersect(_db.postcategories.where(y=>y.posts.any(p => p.id==id))).any()) .orderbydescending(x => x.id).take(20) .tolist();
is best way?
i think need select primary key of postcatagories during intersect:
[childactiononly] public partialviewresult getrelatedpost(int id) { var relatedposts = _db.posts.select(x => new { x.id, x.title, x.slug, x.image, x.isactive,x.posttype,x.postcategories }) .where(x => x.isactive && x.id != id && x.postcategories.select(y => y.id).intersect(_db.postcategories.select(y => y.id)).any()) .orderbydescending(x => x.id).take(20) .tolist(); }).any()) .orderbydescending(x => x.id).take(20) .tolist(); }
Comments
Post a Comment