[英]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. HangFire作业使用此新方法。 This is how I add it to the Configure
method of the Startup.cs
这就是我将其添加到Startup.cs
的Configure
方法中的方式
// 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
: 这是ProjectDbContext
的DbSet:
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. 即使在此DbSet上进行选择,似乎也无法正常工作,我也不明白自己做错了什么。 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. 问题是我在循环内调用LogRepeatedTask
并抛出错误,表明正在发生另一笔交易。
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. 我只是从那里删除,将Ids添加到字典中,然后从那里开始使用。
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. 因此,没有奇怪的行为。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.