Asp.net mvc 数据库中未保存任何内容,也没有错误,多对多关系
在用户和帖子之间建立多对多关系。我想在post表和具有postID和登录用户ID的关联表中创建新值。没有错误消息,运行应用程序时似乎可以创建post,但任何表中都没有保存任何内容。我可以看到,当我运行debug时,它会执行所有步骤,甚至保存到数据库。怎么了 后模型Asp.net mvc 数据库中未保存任何内容,也没有错误,多对多关系,asp.net-mvc,entity-framework,asp.net-mvc-4,many-to-many,code-first,Asp.net Mvc,Entity Framework,Asp.net Mvc 4,Many To Many,Code First,在用户和帖子之间建立多对多关系。我想在post表和具有postID和登录用户ID的关联表中创建新值。没有错误消息,运行应用程序时似乎可以创建post,但任何表中都没有保存任何内容。我可以看到,当我运行debug时,它会执行所有步骤,甚至保存到数据库。怎么了 后模型 public class Post { public Post() { this.ApplicationUser = new HashSet<Application
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; }
}
公共类职位
{
公职人员职位()
{
this.ApplicationUser=new HashSet();
}
公共int PostId{get;set;}
公共字符串消息{get;set;}
public DateTime MessageDate{get;set;}
公共虚拟ICollection应用程序用户{get;set;}
}
识别模型
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; }
}
公共类应用程序用户:IdentityUser
{
公共异步任务GenerateUserIdentityAsync(用户管理器)
{
//注意authenticationType必须与CookieAuthenticationOptions.authenticationType中定义的类型匹配
var userIdentity=wait manager.CreateIdentityAsync(这是DefaultAuthenticationTypes.ApplicationOkie);
//在此处添加自定义用户声明
返回用户身份;
}
公共应用程序用户()
{
this.Posts=newhashset();
}
公共虚拟ICollection Posts{get;set;}
}
和我的create函数创建一个新帖子
[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);
}
[HttpPost]
[ValidateAntiForgeryToken]
公共操作结果创建([Bind(Include=“PostId,Message,MessageDate”)]Post-Post)
{
var manager=Request.GetOwinContext().GetUserManager();
var userId=User.Identity.GetUserId();
var user=manager.FindById(userId);
if(ModelState.IsValid)
{
user.Posts.Add(post);
db.SaveChanges();
返回操作(“索引”);
}
返回视图(post);
}
我在用户的所有变量(manager、userId、user)和三个表(Posts、AspNetUsers和ApplicationUserPost)中都有值
更新
尝试附加时出错(以及CodeNotFound中的解决方案)
错误1“System.Data.Entity.IDbSet”
不包含“FindById”的定义,并且没有扩展方法
“FindById”接受类型为的第一个参数
“System.Data.Entity.IDbSet”可以是
找到(是否缺少using指令或程序集引用?)
错误2“FreePost.Models.ApplicationDbContext”不包含
“Attach”和无扩展方法“Attach”的定义接受
“FreePost.Models.ApplicationDbContext”类型的第一个参数可能是
找到(是否缺少using指令或程序集引用?)
第一条错误消息是我选择使用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");
}
我尝试此操作时收到两条错误消息。我已经更新了我的第一篇帖子(太长,无法发表评论)。@Xtreme我编辑了我的答案。您必须使用
db.Users.Attatch
而不是db.Attach
。和db.Users.Find
而不是db.Users.FindById
我编辑了我的答案。您必须使用db.Users.Attatch
而不是db.Attach
。和db.Users.Find
而不是db.Users.FindById
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");
}