I have two models : UserProfile
public class UserProfile
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ApplicationUser ApplicationUser { get; set; }
public virtual ICollection<UserPost> UserPost { get; set; }
}
UserPost:
public class UserPost
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public string Id { get; set; }
public string PostTitle { get; set; }
public virtual UserProfile UserProfile { get; set; }
public string Contents { get; set; }
}
UserProfile has a one-to-one relationship with AspNetUser.
UserProfile has a one-to-many relationship with UserPost.
When I'm adding UserPost to the database in the Create method in my controller I get a System.Data.Entity.Infrastructure.DbUpdateException
[HttpPost]
[ValidateAntiForgeryToken]
[Authorize]
public ActionResult Create([Bind(Include = "PostTitle, Content")] UserPost post)
{
if (ModelState.IsValid)
{
UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(db));
var user = UserManager.FindById(User.Identity.GetUserId());
post.UserProfile = user.UserProfile;
db.UserPosts.Add(post);
db.SaveChanges();//error here
return RedirectToAction("Index");
}
return View(post);
}
System.Data.Entity.Infrastructure.DbUpdateException occurred HResult=0x80131501 Message=An error occurred while saving entities that do not expose foreign key properties for their relationships. The EntityEntries property will return null because a single entity cannot be identified as the source of the exception. Handling of exceptions while saving can be made easier by exposing foreign key properties in your entity types. See the InnerException for details.
Inner Exception 1: UpdateException: An error occurred while updating the entries. See the inner exception for details.
Inner Exception 2: SqlException: Cannot insert the value NULL into column 'Id', table 'aspnet-project12017.dbo.UserPosts'; column does not allow nulls. INSERT fails. The statement has been terminated.