c# - MongoDB - How to model recursive relation (categories) -
i'm working on application have categories it's entries. each entry have 1 category. concern how model categories in order achieve cleanest code , design.
this how thinking implement category entity - approach 1:
public class category : entity { public string name { get; set; } public string desc { get; set; } public int guiorder { get; set; } public list<category> categories { get; set; } }
in order achieve nested categories , instantiate them in way:
var cat1 = new category() { name = "bikes", desc = "mountain, city, you-name-it have bikes.", guiorder = 1, categories = new list<category>() { new category() { name = "sub 1", desc = "sub 1 description.", guiorder = 1, //id = } } };
this how document in mongodb. can see in "sub 1", id commented out, because entity definition nested category mongodb not generate key, i'll have explicitly in application, like:
subcat1.id = new bsonobjectidgenerator().generateid(categoryrepository.collection, subcat1).tostring();
and since don't have reference "subdocument1" in object initializer, have done later, probalz recursively before submitting object. seems bit awkward.
as alternative, following entity definition (approach 2):
public class category : entity { public string name { get; set; } public string desc { get; set; } public int guiorder { get; set; } public category parent { get; set; } }
since categories flattened relational approach , don't here mongo insert whole objects, not objectids only:
{ "_id" : objectid("53413657e42c3c16582cda70"), "name" : "bikes", "desc" : "mountain, city, you-name-it have bikes.", "parent" : null } { "_id" : objectid("53413657e42c3c16582cda72"), "name" : "sub 1", "desc" : "sub 1 description.", "parent" : { "_id" : objectid("53413657e42c3c16582cda70"), "name" : "bikes", "desc" : "mountain, city, you-name-it have bikes.", "parent" : null } } { "_id" : objectid("53413657e42c3c16582cda73"), "name" : "sub 2", "desc" : "sub 2 description.", "parent" : { "_id" : objectid("53413657e42c3c16582cda70"), "name" : "bikes", "desc" : "mountain, city, you-name-it have bikes.", "parent" : null } }
so concerns are: approach 1 - how seek through categories efficiently (they nested @ 4 levels)? let's feature: "show in category"... assigning obejctid on application level bad practice? doubt need sharding ever...
or approach 2 if "main" category changes? - i'd have change on several places. deep hirearchy can messy , repetitive.
i appreciate feedback on solution better , proposed improvements. can expect problems 1 or another? better picture - these categories not changing (i might not implement ui manipulation).
Comments
Post a Comment