c# - Add value to Many to Many relationship with EF 5 & ASP.NET MVC 4 -


using code first / mvc 4 / ef 5

i have place object:

   public class place    {       public virtual int placeid { get; set; }       public virtual icollection<tag> tags { get; set; }       public virtual datetime dateadded { get; set; }       public virtual string name { get; set; }       public virtual string url { get; set; } } 

and tag object - many many relationship between them

   public class tag    {       public virtual int tagid { get; set; }       public virtual string name { get; set; }       public virtual string nameplural { get; set; }       public virtual icollection<place> places { get; set; }    } 

i have tags in database - eg "pub", "bakery". when try , assign tag place - says "object reference not set instance of object." example, tags "bakery" & "pub" in database - run this:

place myplace = new place        {           placeid = 1,           name = "shoreditch grind",           url = "shoreditch-grind-cafe",        };          tag mytag = db.tags.single(t => t.name == "bar");         myplace.tags.add(mytag); 

i want assign existing tag "bar" new place i'm creating - errors "object reference not set instance of object.".

i'm sure i'm doing stupid here cannot work out (i'm new mvc). thanks.

you need initialize tags collection, this:

place myplace = new place {     placeid = 1,     name = "shoreditch grind",     url = "shoreditch-grind-cafe",     tags = new list<tag>() };  tag mytag = db.tags.single(t => t.name == "bar");  myplace.tags.add(mytag); 

you move initialization logic constructor of place, little neater , wouldn't have remember create empty list every time create new instance.


Comments

Popular posts from this blog

blackberry 10 - how to add multiple markers on the google map just by url? -

php - guestbook returning database data to flash -

delphi - Dynamic file type icon -