没有保存在数据库中也没有错误,多对多关系

Nothing saved in database and no errors, many to many relation

用户与 post 之间存在多对多关系。我想在 post table 和具有 postID 的关联 table 中创建新值并登录用户 ID。没有错误消息,看起来我可以在 运行 应用程序时创建一个 post,但任何 table 中都没有保存任何内容。当我 运行 调试时,我可以看到它完成了所有步骤,甚至保存到数据库中。怎么了?

Post 型号

public class Post
    {
        public Post()
        {
            this.ApplicationUser = new HashSet<ApplicationUser>();
        }

        public int PostId { get; set; }
        public string Message { get; set; }
        public DateTime MessageDate { get; set; }

        public virtual ICollection<ApplicationUser> ApplicationUser { get; set; }
    }

IdentityModels

 public class ApplicationUser : IdentityUser
    {
       public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
        {
            // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
            var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
            // Add custom user claims here
            return userIdentity;
        }

       public ApplicationUser()
       {
           this.Posts = new HashSet<Post>();
       }

       public virtual ICollection<Post> Posts { get; set; }
    }

我的创建函数创建了一个新的post

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include = "PostId,Message,MessageDate")] Post post)
    {
        var manager = Request.GetOwinContext().GetUserManager<ApplicationUserManager>();
        var userId = User.Identity.GetUserId();
        var user = manager.FindById(userId);

        if (ModelState.IsValid)
        {
            user.Posts.Add(post);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        return View(post);
    }

我在用户(经理、用户 ID、用户)和三个 tables(Posts、AspNetUsers 和 ApplicationUserPost)的所有变量中都有值

更新

我尝试附加时出错(以及来自 CodeNotFound 的解决方案)。

Error 1 'System.Data.Entity.IDbSet' does not contain a definition for 'FindById' and no extension method 'FindById' accepting a first argument of type 'System.Data.Entity.IDbSet' could be found (are you missing a using directive or an assembly reference?)

Error 2 'FreePost.Models.ApplicationDbContext' does not contain a definition for 'Attach' and no extension method 'Attach' accepting a first argument of type 'FreePost.Models.ApplicationDbContext' could be found (are you missing a using directive or an assembly reference?)

第一个错误消息是我选择使用 userManager 的原因。

它不起作用,因为您的 db.SaveChanges 什么都不做。您的上下文什么都不做,因为它对您尝试添加的 Post 实例一无所知。

要解决此问题,您需要首先将 ApplicationUser 的当前实例附加到如下上下文:

var manager = Request.GetOwinContext().GetUserManager<ApplicationUserManager>();
var userId = User.Identity.GetUserId();
var user = manager.FindById(userId);

if (ModelState.IsValid)
{
    // Line below you tell your DbContext to take care of ApplicationUser instance. 
    db.Users.Attach(user); 
    user.Posts.Add(post);
    db.SaveChanges();
    return RedirectToAction("Index");
}

旁注:我将像这样重构您的代码:

if (ModelState.IsValid)
{
    // Move your code that query the database here so you query your database only if the model is valid.
    var userId = User.Identity.GetUserId();

    // You don't need ApplicationUserManager instance to get the ApplicationUser  instance. 
    // If your Post class have a UserId foreign key property then this line is uselesss.
    // Just set the UserId property of Post class.
    var user = db.Users.Find(userId);
    user.Posts.Add(post);
    db.SaveChanges();
    return RedirectToAction("Index");
}