0

This is my tag table, one tag can have multiple posts:

public class Tag
{
    public int TagId { get; set; }
    public string TagName { get; set; }
    public IList<Post> Posts { get; set; }
}

This is my Post class, one post can have multiple tags:

 public class Post
  { 
    [Key]
    public int PostId { get; set; }
    // other related code
    public IList<Tag> Tags { get; set; }
    }

these two classes have created a new table TagPost in database with column(TagId, PostId) Now, i have properly configured with fluent api, data to insert into TagPost table like this:

 modelBuilder.Entity<Tag>()
                    .HasMany(p => p.Posts)
                    .WithMany(t => t.Tags)
                    .Map(m =>
                            {
                                m.ToTable("TagPost");
                                m.MapLeftKey("TagId");
                                m.MapRightKey("PostId");
                            });

and this is my controller to insert the data into post class like this, here i am getting list of selected tags but in for each , at last line it is giving System.NullReferenceException.The code is:

   public JsonResult Post(Post post,IEnumerable<int> MultipleTags)
    {
        post.User = User.Identity.GetUserId<int>();
            foreach (var tagId in MultipleTags)
            {
                var tag = new Tag { TagId = tagId };
              //  db.Tags.Attach(tag); // this avoids duplicate tags
                post.Tags.Add(tag); // getting error here, system.nullReferenceException 
            }
            db.Posts.Add(post);
            db.SaveChanges();
             var usr = db.Users.FirstOrDefault(x => x.Id == post.PostedBy);
            var ret = new
            {
                TagName = string.Join(",", post.Tags.Select(t => t.TagName)),
            };
            return Json( ret,JsonRequestBehavior.AllowGet);

, when i hover, i can see tag contains correct id value, what is wrong here, it was working fine earlier but now its giving here please suggest me something.

neo
  • 75
  • 2
  • 9

1 Answers1

2

You need to initialize your tags list in a constructor:

public class Post
{ 
  [Key]
  public int PostId { get; set; }
  // other related code
  public virtual IList<Tag> Tags { get; set; }

  public Post()
  {
    Tags=new List<Tag>();
  }

}

You should do the same in all entities that have collection navigation properties.

ocuenca
  • 38,548
  • 11
  • 89
  • 102
  • thnks its working but now, new problem, u can see in the edited controller, TagName is returning null still, may be something related to eager loading/ defer loading. plzz see, it should return all the tag name but null reference exception – neo Jan 18 '16 at 13:39
  • I don't thing so. Scalar properties are not lazy loaded. All are loaded when you load an entity, maybe it was not saved properly (if was the case) or you should not have a value for that column – ocuenca Jan 18 '16 at 13:42
  • in database it is properly saved i have checked twice let me check it out once again – neo Jan 18 '16 at 13:44
  • That's odd, are you sure `TagName` property is correctly mapped with that column in your DB? – ocuenca Jan 18 '16 at 13:50
  • still not getting it same error dont know why its returning null it should display all the tag name @octavioccl – neo Jan 18 '16 at 14:04
  • @neo, I suggest you create a new question about your new issue, maybe someone else has happened the same, but I don't find any other logical explanation besides I already have given you before in my comments, sorry my friend – ocuenca Jan 18 '16 at 14:10