这是一个很长的镜头,因为有太多的自定义代码,但希望它很简单。
我有 DatabaseInitializer 类:
/// <summary>
/// Our Database initialsizer, which inherits CreateDatabaseIfNotExists. We could use DropCreateDatabaseWhenModelChanges or DropCreateDatabaseAlways as well.
/// </summary>
public class DatabaseInitializer : CreateDatabaseIfNotExists<DatabaseContext>
{
/// <summary>
/// Method to insert our data upon initialization
/// </summary>
/// <param name="context">Our DbConext</param>
protected override void Seed(DatabaseContext context)
{
// Create our User
CreateUser();
// Seed
base.Seed(context);
}
/// <summary>
/// Private method which creates the user
/// </summary>
private void CreateUser()
{
// Create our unit of work
var unitOfWork = new UnitOfWork<DatabaseContext>();
// Create our user service
var service = new UserService<User>(unitOfWork, true, true);
// Get our current date
var now = DateTime.UtcNow;
// Map the user model out
var user = new User()
{
UserName = "j***@*****.co.uk",
Email = "j***@*****.co.uk",
DateCreated = now,
DateModified = now,
LastLoginDate = now
};
// Run our task
var task = Task.Run(async () => {
// Create our user
await service.CreateAsync(user, "********");
// Save the changes to our DbSet
await unitOfWork.SaveChangesAsync();
});
// Wait for the async task to complete
task.Wait();
}
}
现在的问题是,它似乎永远不会完成。 我想这可能是因为异步任务,但我无法确定。 我知道没有太多事情可以继续,但就像我说的那样,我希望它很简单,因为向你展示我的UnitOfWork类与我的UserService一起工作将会是很多代码。请放心,他们在其他项目中工作得很好。
的UnitOfWork
这就是构成我的 UnitOfWork 类的原因:
public class UnitOfWork<TContext> : IUnitOfWork where TContext : DbContext, new()
{
private readonly DbContext context;
private Dictionary<Type, object> repositories;
public DbContext Context { get { return this.context; } }
public UnitOfWork()
{
this.context = new TContext();
repositories = new Dictionary<Type, object>();
}
public IRepository<TEntity> GetRepository<TEntity>() where TEntity : class
{
if (repositories.Keys.Contains(typeof(TEntity)))
return repositories[typeof(TEntity)] as IRepository<TEntity>;
var repository = new Repository<TEntity>(context);
repositories.Add(typeof(TEntity), repository);
return repository;
}
public async Task SaveChangesAsync()
{
try
{
await this.context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException ex)
{
ex.Entries.First().Reload();
}
}
public void Dispose()
{
this.context.Dispose();
}
}
答案 0 :(得分:0)
如评论中所述,您需要使用相同的datacontext。
在UnitOfWork<TContext>
类中添加一个构造函数,该构造函数可以将现有上下文作为参数:
public UnitOfWork(TContext context)
{
this.context = context;
repositories = new Dictionary<Type, object>();
}
然后在你的CreateUser方法:
private void Createuser(DatabaseContext context)
{
var unitOfWork = new UnitOfWork<DatabaseContext>(context);
...
}