c# - How do I write a where query to only include 1 entity of child -
i have entities
blog{ blogid, name, creatoruserid } blogsettings{ blogid, userid, column1 } now have method accepts blogid , userid , querying on blog (not blogsettings)
blog contains collection of blogsettings.
how should it?
if write context.blogs.include("blogsettings").where( b => b.blogid == blogid) inefficient since need blogsettings userid == userid.
note: not querying on blogsettings. can see querying on blog collection.
var blogwithsetting = context.blogs .where(b => b.blogid == blogid) .select(b => new { blog = b, blogsetting = b.blogsettings.firstordefault(bs => bs.userid == userid) }) .singleordefault(); if (blogwithsetting != null) { blog blog = blogwithsetting.blog; // } such projection way result in single roundtrip database because eager loading include doesn't support filtering or sorting on included child collections. blog.blogsettings populated automatically single loaded blogsetting, if don't disable change tracking , if relationship not many-to-many. otherwise must fill collection manually using properties of result object:
if (blogwithsetting != null) { blog blog = blogwithsetting.blog; blog.blogsettings = new list<blogsetting>(); blog.blogsettings.add(blogwithsetting.blogsetting); // }
Comments
Post a Comment