c# - Entity object's virtual list is null, how do I initialise it? -
i have 2 entities blogpost , tag, , want able add/retrieve list of tags associated each blogpost, list of blogposts associated each tag.
in theory, should fine, there table blogposttags link them blogpostid tagid.
the problem have when trying add together tags new blogpost, blogpost.tags property null.
how initialise list, empty list, can add together tags it?
public class blogpost { public int blogpostid { get; set; } public string blogtitle { get; set; } public string blogcontent { get; set; } public virtual list<tag> tags { get; set; } } public class tag { public int tagid { get; set; } public string tagname { get; set; } public virtual list<blogpost> blogposts { get; set; } } somewhere tags created so:
tag tag1 = context.tags.create(); tag1.tagname = "test1"; context.tags.add(tag1); context.savechanges(); and want able add together them new blogpost:
blogpost post = context.blogposts.create(); post.blogtitle = "test post"; post.blogcontent = "this test blog , such lorem bacon."; post.dateposted = datetime.now; post.tags.add(tag1); context.blogposts.add(post); context.savechanges(); but post.tags throws object reference not set instance of object.
initialise list in constructor
public class blogpost { public int blogpostid { get; set; } public string blogtitle { get; set; } public string blogcontent { get; set; } public virtual list<tag> tags { get; set; } public blogpost() { tags = new list<tag>(); } } and same other class
public class tag { public int tagid { get; set; } public string tagname { get; set; } public virtual list<blogpost> blogposts { get; set; } public tag() { blogposts = new list<blogpost>(); } } c# entity-framework-5
No comments:
Post a Comment