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.