ASP.Net MVC-实体框架6有时会创建重复记录吗?

时间:2018-09-18 07:46:08

标签: c# asp.net-mvc transactions entity-framework-6

我有一个使用EF6的ASP.Net MVC 5应用程序。我正在使用Ninject进行依赖项注入。

我有以下代码可向票证添加评论。但是有时它会创建重复的记录。为什么会发生这种情况,我该如何解决?

总而言之,我最终要添加3条评论,而不是重复添加2条用户评论-这只是偶尔发生。

 var ticket = _unitOfWork.TicketRepository.GetTicket(dto.TicketId);

 using (var transaction = _unitOfWork.BeginTransaction())
 {
       try
       {
             // Add user posted comment
             var comment = new Comment
             {
                TicketId = dto.TicketId,
                Comments = dto.Comments
             };

             ticket.AddComment(comment);

             // save changes
             _unitOfWork.Complete();

             // Add a system comment
             ticket.AddComment(new Comment                    
             {
                TicketId = dto.TicketId,
                Comments = "<b>System Comment:</b><br>Some auto comment"
             });

             _notificationService.Send(ticket, comment, User.Identity.GetUserId());

             // save changes
             _unitOfWork.Complete();

             // Commit
             transaction.Commit();

             return Ok(Mapper.Map<CommentDto>(_unitOfWork.CommentRepository.GetComment(comment.Id)));

      }
      catch (Exception ex)
      {
            transaction.Rollback();

            return InternalServerError(ex);
       }

 }

这些是我的unitOfWork类中的方法:

 public void Complete()
 {
        _context.SaveChanges();
 }

 public DbContextTransaction BeginTransaction()
 {
        return _context.Database.BeginTransaction();
 }

这是我的Ticket类中的添加注释方法:

 public void AddComment(Comment comment)
 {
        Comments.Add(comment);
 }

*更新*

我知道的唯一使用数据库上下文的事情是发送作业的后台作业,该作业使用hangfire每分钟运行一次,但不使用unitofwork-请参见下面的代码:

 [DisallowConcurrentExecution]
 public class EmailJob : IJob 
 {

    private readonly Logger _logger = LogManager.GetCurrentClassLogger();
    private readonly IUserNotificationRepository _userNotificationRepository;
    private readonly INotificationMailer _notificationMailer;
    private readonly ApplicationDbContext _context;

    public EmailJob()
    {
        _context = new ApplicationDbContext();
        _userNotificationRepository = new UserNotificationRepository(_context);
        _notificationMailer = new NotificationMailer();
    }


    public EmailJob(IUserNotificationRepository userNotificationRepository,
        INotificationMailer notificationMailer)
    {
        _userNotificationRepository = userNotificationRepository;
        _notificationMailer = notificationMailer;
    }

    // Use for hangfire
    public void Execute()
    {
        SendMail(_logger);
    }

    private void SendMail(Logger logger)
    {
        // some mail sending code...

        // Persist changes back to database
         _context.SaveChanges();
    }
}

有什么主意吗?

0 个答案:

没有答案