简体   繁体   中英

Asp.Net Core 2,Entity Framework and Services. Weird Behaviour

I'm adding a new method to a service that already works. This new method is used by a HangFire job. This is how I add it to the Configure method of the Startup.cs

// Create the daily tasks
RecurringJob.AddOrUpdate<ITaskService>(x => x.CreateRecurringTasks(), Cron.Daily(0));

And this is the constructor of the service. Note that I create the DB context in the start so I don't have transaction problems when using it inside a controller.

public TaskService(
    IMapper mapper,
    INotificationService notificationService,
    IConfiguration configuration
)
{

    var opts = new DbContextOptionsBuilder<ProjectDbContext>();
    opts.UseSqlServer(configuration.GetConnectionString("DefaultConnection"));
    _dbContext = new ProjectDbContext(opts.Options);

    _configuration = configuration;
    _mapper = mapper;
    _notificationService = notificationService;
}

My problem is that the method below won't add the row in the database.

void LogRepeatedTask(long copiedTaskId, long originalTaskId) {
    _dbContext.TaskRepeatLogs.Add(new Data.Models.TaskRepeatLog
    {
        CopiedTaskId = copiedTaskId,
        OriginalTaskId = originalTaskId,
        UtcDate = DateTime.UtcNow
    });
    _dbContext.SaveChanges();
}

This is the model. As you can see it is pretty simple:

public class TaskRepeatLog
{
    public long Id { get; set; }
    public long OriginalTaskId { get; set; }
    public long CopiedTaskId { get; set; }
    public DateTime UtcDate { get; set; }
}

And this is the DbSet in the ProjectDbContext :

public DbSet<TaskRepeatLog> TaskRepeatLogs { get; set; }

Everything seems pretty straightforward to me but I can't understand why the method is not working. Even the select on this DbSet seems not to work properly and I don't understand what I did wrong. Can you help me?

Thanks

I found the issue. The problem was that I was calling the LogRepeatedTask inside a loop and it was throwing an error saying that there was another transaction happening.

This is where I was calling the function. I just removed from there, added the Ids to a dictionary and I'm using from there.

    var tasks = _dbContext.Tasks
        .Include(i => i.RepeatConfig)
        .Where(p => p.RepeatTask && p.RepeatConfig != null && p.CopiedFromTaskId == null);

    if (tasks != null)
    {
        foreach (var task in tasks)
        {
            // I was calling the method here. 
        }
    }

So there was no weird behavior.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM