简体   繁体   中英

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

Using Code First / MVC 4 / EF 5

I have a 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 a Tag object - with a many to 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 some tags in the database already - eg "Pub", "Bakery". When I try and assign a tag to a place - it always says "Object reference not set to an instance of an object." For example, Tags "Bakery" & "Pub" are already in the database - then I 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 to assign the existing tag "Bar" to this new place I'm creating - but it always errors with "Object reference not set to an instance of an object.".

I'm sure I'm doing something really stupid here but just cannot work out what it is (I'm new to MVC). Thanks.

You need to initialize the Tags collection, like 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 could move the initialization logic to the constructor of Place , which would be a little neater and you wouldn't have to remember to create an empty list every time you create a new instance.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM