My DAL is based on Entity Framework Code First.
I have a post model and a tag model. One post can have several posts attached.
Here is my post:
public class Post
{
[Key]
public int PostID { get; set; }
...
public virtual ICollection<Tag> Tags { get; set; }
}
Here is my tag:
public class Tag
{
[Key]
public int TagID { get; set; }
[Required, StringLength(50)]
public string Name { get; set; }
public virtual ICollection<Post> Posts { get; set; }
}
When I save my post, I don't have any errors but nothing is saved in the DB.
As you can see on the screenshot above the TagID is 0 and I don't know why???
Any idea? Suggestions?
My tables are correctly created in Sql Server.
Thanks.
PS: My code must be ok because I copy/paste it from another location (where it works).
UPDATE
Here is the code to update tag entities (under a specific post)
Tag t = m_TagRepository.GetTag(tag.Trim().ToUpper());
if (t == null) t = new Tag { Name = tag.Trim().ToUpper() };
post.Tags.Add(t);
Here is the code to save changes to a post (and tag below)
public void SavePost(Post post)
{
if (post.PostID == 0)
{
m_Context.Posts.Add(post);
}
else
{
var entry = m_Context.Entry(post);
entry.State = EntityState.Modified;
}
m_Context.SaveChanges();
}
I get the post back from the Edit view page:
[Authorize, HttpPost, ValidateInput(false), Theme("Admin")]
public ActionResult Edit(PostFullViewModel postToEdit)
{
if (!ModelState.IsValid)
return View();
Post post = Mapper.Map<PostFullViewModel, Post>(postToEdit);
m_PostBusiness.UpdateTags(post, postToEdit.TagString);
m_PostBusiness.SavePost(post);
TempData.SetStatusMessage(Strings.Post_SavedSuccessfully);
return RedirectToAction("Manage");
}