当我尝试添加评论时,出现以下错误:
ObjectDisposedException:无法访问已处置的对象.
当代码运行第二行时:
m_context.Comments.Add(comment);
m_context.SaveChanges();
Run Code Online (Sandbox Code Playgroud)
为什么要处理上下文?如果将TryAddComment方法移动到控制器中,它不会提前调用Dispose.
这是我的Controller和Repository类的样子(简化).
CommentsController.cs:
public class CommentsController : Controller
{
private ICommentRepository m_commentRepository;
public CommentsController(ICommentRepository commentRepository)
{
m_commentRepository = commentRepository;
}
// POST: api/Comments
[HttpPost]
public async Task<IActionResult> PostComment([FromBody] CommentAddViewModel commentVM)
{
Comment comment = new Comment
{
ApplicationUserId = User.GetUserId(),
PostId = commentVM.PostId,
Text = commentVM.Text
};
bool didAdd = m_commentRepository.TryAddComment(comment);
if (!didAdd)
{
return new HttpStatusCodeResult(StatusCodes.Status409Conflict);
}
return CreatedAtRoute("GetComment", new { id = comment.CommentId }, comment);
}
}
Run Code Online (Sandbox Code Playgroud)
CommentRepository.cs:
public class CommentRepository : ICommentRepository, …Run Code Online (Sandbox Code Playgroud) 你会如何播种用户?我在这里关注他们的文档,但他们只展示了如何为ApplicationDbContext直接插入的数据设定种子.
在帐户控制器中,UserManager通过DI创建.如何在Seed方法中实例化UserManager?
public class SeedData
{
public static void Initialize(IServiceProvider serviceProvider)
{
var context = serviceProvider.GetService<ApplicationDbContext>();
var userManager = serviceProvider.GetService<UserManager<ApplicationUser>>();
Run Code Online (Sandbox Code Playgroud)
然后在Configure方法的Startup.cs中:
SeedData.Initialize(app.ApplicationServices);
Run Code Online (Sandbox Code Playgroud) 这是我的模特:
public class Post
{
[Key]
public int PostId { get; set; }
[Required]
[MaxLength(140)]
public string Title { get; set; }
[Required]
public string ApplicationUserId { get; set; }
public ApplicationUser ApplicationUser { get; set; }
public ICollection<Comment> Comments { get; set; }
}
public class Comment
{
[Key]
public int CommentId { get; set; }
[Required]
[StringLength(1000)]
public string Text { get; set; }
[Required]
public int PostId { get; set; }
[Required]
public string ApplicationUserId { get; …Run Code Online (Sandbox Code Playgroud)