How to use manual references when inserting and retrieving relational data using MongoDb and its C# driver -
as may obvious of question, coming relational database way of thinking (sql server) , using orms (entity framework). want same things in mongodb , having troubles it.
let me explain simple scenario. suppose have user, , each user can write posts (a one-to-many relationship in sql). working simple case.
i've read 2 or 3 articles (and mongodb's original documentation) when use manual references
, dbref
s , when embed documents within each other. , here going needing posts
without users
(like when visitor of website wants see posts) , users
without posts
(like managing user profiles or something), believe these 2 entities (documents) should separated.
now let's our hands little dirty code. in entity framework implement idea above this:
//user model public class user { public int id { get;set; } public string name { get; set; } public list<post> posts { get; set; } public user { this.posts = new list<post>(); } } //post model public class post { public int id { get; set; } public string body { get; set; } public datetime datecreated { get; set; } public user user { get; set; } } //getting data pretty easy using entity framework //suppose context created beforehand var usersandtheirposts = context.users.include(x => x.posts).where(x => x.id > 5).tolist(); //getting first users post list<post> firstuserposts = usersandtheirposts.firstordefault().posts; //updating posts have been created after date x foreach (var post in firstusersposts.where(x => x.datacreated > datex)) { //do posts } context.savechanges(); //the actual updating happens here
what tried implement same thing in mongodb (i trying use manual references
since don't think dbrefs way go scenario (additional unwanted overload):
//user class public class user { [bsonid] public objectid id { get; set; } [bsonelement("name")] public string name { get; set; } [bsonelement("posts")] [bsonignoreifnull] public list<post> plants { get; set; } } // public class post { [bsonid] public objectid id { get; set; } [bsonelement("body")] public string body { get; set; } [bsonelement("date_created")] public datetime datecreated { get; set; } [bsonelement("users_id")] public user user { get; set; } } //do other stuff should done
but of course, scheme not working , inserting document of type user
example, causes creation of wired objects , documents (obviously)
so ultimate question this: how can achieve same functionality had in entity framework in mongodb using manual references
, in short able these 2 things:
- somehow select users , posts above (the
include
method) using filter , deserialize 1user
object - get user's
posts
, post'suser
implemented in models entity framework uses
thanks in advance
Comments
Post a Comment