我遇到Windows服务,实体框架和工作单元模式的问题。我的服务定期运行(使用System.Treading.Timer)并查询数据库以生成HTML报告。使用UnitOfWork并尝试查询数据库会引发异常:
"支持' DataContext'自从以来情境发生了变化 数据库已创建。考虑使用Code First Migrations进行更新 数据库(http://go.microsoft.com/fwlink/?LinkId=238269)。"
问题是我的模型与物理数据库模式同步。我怀疑它可能是多线程问题,但我也尝试使用另一个计时器(System.Timers.Timer),它不应该是多线程的,并且会发生同样的错误。我该怎么办才能修复它?谢谢你的帮助! 这是我的代码:
public class UnitOfWork : IUnitOfWork
{
private DataContext db;
public UnitOfWork()
{
db = new DataContext();
}
private IDailyRequestsRepository dailyRequestsRepository;
public IDailyRequestsRepository DailyRequestsRepository
{
get
{
if (this.dailyRequestsRepository == null)
{
this.dailyRequestsRepository = new DailyRequestsRepository(db);
}
return dailyRequestsRepository;
}
}
}
public class DailyRequestsRepository : IDailyRequestsRepository
{
private DataContext db;
public DailyRequestsRepository(DataContext db)
{
this.db = db;
}
public IQueryable<DailyRequest> GetAllWithDailyRequestItemsByDate(DateTime date)
{
return db.DailyRequests.Where(d => DbFunctions.TruncateTime(d.Date) == date.Date);
}
}
JobService(在OnStart中初始化计时器):
protected override void OnStart(string[] args)
{
TimerCallback callback = new TimerCallback(SomeMethod);
myTimer = new Timer(callback, this, whenToCall, interval);
}
SomeMethod(来自上面的TimerCallback):
public static void SomeMethod(object state) // TimerCallback required this parameter "object state"
{
if (job == null || job .Status != TaskStatus.Running)
{
job = Task.Factory.StartNew((Action)Execute);
try
{
job.Wait();
}
catch (AggregateException ex)
{
// Exceptions logging...
log.Error(ex);
}
}
}
public static void Execute()
{
using (IUnitOfWork unitOfWork = new UnitOfWork())
{
var dailyRequests = unitOfWork.DailyRequestsRepository.GetAllWithDailyRequestItemsByDate(DateTime.Today);
}
}