Entity framework 如何将IDbContext传递到DBMigOptionsConfiguration

Entity framework 如何将IDbContext传递到DBMigOptionsConfiguration,entity-framework,entity-framework-5,code-first,dbcontext,Entity Framework,Entity Framework 5,Code First,Dbcontext,首先从大量资源中使用EF5代码实现了通用存储库、工作单元模式,并提出了以下程序集 接口、上下文、模型、存储库、工作单元 在上下文程序集中,我有一个包含Configuration.cs的migrations文件夹 internal sealed class Configuration : DbMigrationsConfiguration<Context.SportsContext> { public Configuration() { Automati

首先从大量资源中使用EF5代码实现了通用存储库、工作单元模式,并提出了以下程序集

接口、上下文、模型、存储库、工作单元

在上下文程序集中,我有一个包含Configuration.cs的migrations文件夹

internal sealed class Configuration : DbMigrationsConfiguration<Context.SportsContext>
{
    public Configuration()
    {
        AutomaticMigrationsEnabled = true;
    }

    protected override void Seed(Context.SportsContext context)
    {
        //  This method will be called after migrating to the latest version.

        //  You can use the DbSet<T>.AddOrUpdate() helper extension method 
        //  to avoid creating duplicate seed data. E.g.
        //
        //    context.People.AddOrUpdate(
        //      p => p.FullName,
        //      new Person { FullName = "Andrew Peters" },
        //      new Person { FullName = "Brice Lambson" },
        //      new Person { FullName = "Rowan Miller" }
        //    );
        //
    }
}
内部密封类配置:dbmigtorinsconfiguration
{
公共配置()
{
AutomaticMiggerationsEnabled=真;
}
受保护的覆盖无效种子(Context.sportcontext)
{
//迁移到最新版本后将调用此方法。
//您可以使用DbSet.AddOrUpdate()助手扩展方法
//避免创建重复的种子数据。
//
//context.People.AddOrUpdate(
//p=>p.FullName,
//新人{FullName=“安德鲁·彼得斯”},
//新人{FullName=“Brice Lambson”},
//新人{FullName=“Rowan Miller”}
//    );
//
}
}
正如您所看到的,此DbMigrationsConfiguration接受my SportsContext,它也在contexts程序集(contexts文件夹)中定义

公共类SportContext:IDbContext
{
私有只读DbContext\u context;
公共体育环境()
{
_上下文=新的DbContext(“SportContext”);
}
公共空间处置()
{
_context.Dispose();
}
公共IDbSet GetEntitySet(),其中T:class
{
返回_context.Set();
}
public void ChangeState(T实体,EntityState状态),其中T:class
{
_context.Entry(entity).State=State;
}
公共void SaveChanges()
{
_SaveChanges();
}
}
这将实现接口程序集中定义的IDbContext

public interface IDbContext : IDisposable
{
    IDbSet<T> GetEntitySet<T>() where T : class;
    void ChangeState<T>(T entity, EntityState state) where T : class;
    void SaveChanges();
}
公共接口IDbContext:IDisposable { IDbSet GetEntitySet(),其中T:class; void ChangeState(T实体,EntityState状态),其中T:class; void SaveChanges(); } 在我的工作单元集合中,我有以下课程

public class SportUnitOfWork : IUnitofWork
{
    private readonly IDbContext _context;

    public SportUnitOfWork()
    {
        _context = new SportsContext();
    }

    private GenericRepository<Team> _teamRepository;
    private GenericRepository<Fixture> _fixtureRepository;

    public GenericRepository<Team> TeamRepository
    {
        get { return _teamRepository ?? (_teamRepository = new GenericRepository<Team>(_context)); }
    }

    public GenericRepository<Fixture> FixtureRepository
    {
        get { return _fixtureRepository ?? (_fixtureRepository = new GenericRepository<Fixture>(_context)); }
    }

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

    public IDbContext Context
    {
        get { return _context; }
    }

    private bool _disposed;

    protected virtual void Dispose(bool disposing)
    {
        if (!_disposed)
        {
            if (disposing)
            {
                _context.Dispose();
            }
        }
        _disposed = true;
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

}
公共类SportUnitOfWork:IUnitofWork
{
私有只读IDbContext _context;
公共体育联合会()
{
_context=新的sportcontext();
}
私人通用存储库(teamRepository);
专用通用存储库(fixtureRepository);;
公共通用存储库
{
获取{return\u teamRepository???(\u teamRepository=newgenerirepository(\u context));}
}
公共通用存储固定库
{
获取{return{fixtureRepository???({fixtureRepository=newgenericreepository(_context));}
}
公共作废保存()
{
_SaveChanges();
}
公共语境
{
获取{return\u context;}
}
私人住宅;
受保护的虚拟void Dispose(bool disposing)
{
如果(!\u已处置)
{
如果(处置)
{
_context.Dispose();
}
}
_这是真的;
}
公共空间处置()
{
处置(真实);
总干事(本);
}
}
例如,我在存储库程序集中添加了GenericRepository类

public class GenericRepository<T> : IGenericRepository<T> where T : class
{
    private IDbContext _context;

    public GenericRepository(IDbContext context)
    {
        _context = context;
    }

    public GenericRepository(IUnitofWork uow)
    {
        _context = uow.Context;
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    protected virtual void Dispose(bool disposing)
    {
        if (!disposing) return;

        if (_context == null) return;
        _context.Dispose();
        _context = null;
    }

    public void Add(T entity)
    {
        _context.GetEntitySet<T>().Add(entity);
    }

    public void Update(T entity)
    {
        _context.ChangeState(entity, EntityState.Modified);
    }

    public void Remove(T entity)
    {
        _context.ChangeState(entity, EntityState.Deleted);
    }

    public T FindSingle(Expression<Func<T, bool>> predicate = null, params Expression<Func<T, object>>[] includes)
    {
        var set = FindIncluding(includes);
        return (predicate == null) ? set.FirstOrDefault() : set.FirstOrDefault(predicate);
    }

    public IQueryable<T> Find(Expression<Func<T, bool>> predicate = null, params Expression<Func<T, object>>[] includes)
    {
        var set = FindIncluding(includes);
        return (predicate == null) ? set : set.Where(predicate);
    }

    public IQueryable<T> FindIncluding(params Expression<Func<T, object>>[] includeProperties)
    {
        var set = _context.GetEntitySet<T>();

        if (includeProperties != null)
        {
            foreach (var include in includeProperties)
            {
                set.Include(include);
            }
        }

        return set.AsQueryable();
    }

    public int Count(Expression<Func<T, bool>> predicate = null)
    {
        var set = _context.GetEntitySet<T>();
        return (predicate == null) ? set.Count() : set.Count(predicate);
    }

    public bool Exist(Expression<Func<T, bool>> predicate = null)
    {
        var set = _context.GetEntitySet<T>();
        return (predicate == null) ? set.Any() : set.Any(predicate);
    }
}
公共类GenericRepository:IGenericRepository其中T:class
{
私有上下文_上下文;
公共一般报告(IDbContext)
{
_上下文=上下文;
}
公共总报告(IUnitofWork uow)
{
_context=uow.context;
}
公共空间处置()
{
处置(真实);
总干事(本);
}
受保护的虚拟void Dispose(bool disposing)
{
如果(!处理)返回;
if(_context==null)返回;
_context.Dispose();
_上下文=空;
}
公共无效添加(T实体)
{
_context.GetEntitySet().Add(实体);
}
公共无效更新(T实体)
{
_ChangeState(实体,EntityState.Modified);
}
公共无效删除(T实体)
{
_context.ChangeState(entity,EntityState.Deleted);
}
公共T FindSingle(表达式谓词=null,参数表达式[]包含)
{
变量集=FindIncluding(包括);
return(谓词==null)?set.FirstOrDefault():set.FirstOrDefault(谓词);
}
公共IQueryable查找(表达式谓词=null,参数表达式[]包含)
{
变量集=FindIncluding(包括);
return(谓词==null)?set:set.Where(谓词);
}
公共可查询的FindIncluding(参数表达式[]包含属性)
{
var set=_context.GetEntitySet();
if(includeProperties!=null)
{
foreach(包含在includeProperties中的var)
{
集合。包括(包括);
}
}
返回set.AsQueryable();
}
公共整数计数(表达式谓词=null)
{
var set=_context.GetEntitySet();
return(谓词==null)?set.Count():set.Count(谓词);
}
公共布尔存在(表达式谓词=null)
{
var set=_context.GetEntitySet();
return(谓词==null)?set.Any():set.Any(谓词);
}
}
我遇到的问题是,从DBmigRationalConfiguration继承的Configuration类需要一个DbContext参数

错误为错误1在泛型类型或方法“System.Data.Entity.Migrations.DbMigrationsConfiguration”中,类型“Context.Context.SportContext”不能用作类型参数“TContext”。没有从“Context.Context.sportcontext”到“System.Data.Entity.DbContext”的隐式引用转换

我可以将SportsContext更改为也从DbContext继承,但是我需要在UnitsOfWork程序集中添加对EntityFramework 5的引用,因为我们可能希望在不使用任何引用的情况下更改或删除每个层
public class GenericRepository<T> : IGenericRepository<T> where T : class
{
    private IDbContext _context;

    public GenericRepository(IDbContext context)
    {
        _context = context;
    }

    public GenericRepository(IUnitofWork uow)
    {
        _context = uow.Context;
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    protected virtual void Dispose(bool disposing)
    {
        if (!disposing) return;

        if (_context == null) return;
        _context.Dispose();
        _context = null;
    }

    public void Add(T entity)
    {
        _context.GetEntitySet<T>().Add(entity);
    }

    public void Update(T entity)
    {
        _context.ChangeState(entity, EntityState.Modified);
    }

    public void Remove(T entity)
    {
        _context.ChangeState(entity, EntityState.Deleted);
    }

    public T FindSingle(Expression<Func<T, bool>> predicate = null, params Expression<Func<T, object>>[] includes)
    {
        var set = FindIncluding(includes);
        return (predicate == null) ? set.FirstOrDefault() : set.FirstOrDefault(predicate);
    }

    public IQueryable<T> Find(Expression<Func<T, bool>> predicate = null, params Expression<Func<T, object>>[] includes)
    {
        var set = FindIncluding(includes);
        return (predicate == null) ? set : set.Where(predicate);
    }

    public IQueryable<T> FindIncluding(params Expression<Func<T, object>>[] includeProperties)
    {
        var set = _context.GetEntitySet<T>();

        if (includeProperties != null)
        {
            foreach (var include in includeProperties)
            {
                set.Include(include);
            }
        }

        return set.AsQueryable();
    }

    public int Count(Expression<Func<T, bool>> predicate = null)
    {
        var set = _context.GetEntitySet<T>();
        return (predicate == null) ? set.Count() : set.Count(predicate);
    }

    public bool Exist(Expression<Func<T, bool>> predicate = null)
    {
        var set = _context.GetEntitySet<T>();
        return (predicate == null) ? set.Any() : set.Any(predicate);
    }
}
public abstract class BaseContext : IDbContext
{
    protected DbContext Context;

    public void Dispose()
    {
        Context.Dispose();
    }

    public IDbSet<T> GetEntitySet<T>() where T : class
    {
        return Context.Set<T>();
    }

    public void Add<T>(T entity) where T : class
    {
        DbEntityEntry dbEntityEntry = GetDbEntityEntrySafely(entity);
        dbEntityEntry.State = EntityState.Added;
    }

    public void Update<T>(T entity) where T : class
    {
        DbEntityEntry dbEntityEntry = GetDbEntityEntrySafely(entity);
        dbEntityEntry.State = EntityState.Modified;
    }

    public void Delete<T>(T entity) where T : class
    {
        DbEntityEntry dbEntityEntry = GetDbEntityEntrySafely(entity);
        dbEntityEntry.State = EntityState.Deleted;
    }

    public void SaveChanges()
    {
        // At the moment we are conforming to server wins when handling concurrency issues
        // http://msdn.microsoft.com/en-us/data/jj592904

        try
        {
            Context.SaveChanges();
        }
        catch (DbUpdateConcurrencyException e)
        {
            //Refresh using ServerWins
            var objcontext = ((IObjectContextAdapter) Context).ObjectContext;
            var entry = e.Entries;

            objcontext.Refresh(RefreshMode.StoreWins, entry);

            SaveChanges();
        }
    }

    private DbEntityEntry GetDbEntityEntrySafely<T>(T entity) where T : class
    {
        DbEntityEntry dbEntityEntry = Context.Entry(entity);

        if (dbEntityEntry.State == EntityState.Detached)
        {
            // Set Entity Key
            var objcontext = ((IObjectContextAdapter) Context).ObjectContext;

            if (objcontext.TryGetObjectByKey(dbEntityEntry.Entity))

            Context.Set<T>().Attach(entity);
        }

        return dbEntityEntry;
    }
}
public class FootballContext : BaseContext
{
    public FootballContext(string connectionstringName)
    {
        Context = new BaseFootballContext(connectionstringName);

    }
}
public class BaseFootballContext : DbContext
{
    public BaseFootballContext(string nameOrConnectionString) : base(nameOrConnectionString)
    {
    }

    public IDbSet<Fixture> Fixtures { get; set; }
    public IDbSet<Team> Teams { get; set; }  
}

public class MigrationsContextFactory : IDbContextFactory<BaseFootballContext>
{
    public BaseFootballContext Create()
    {
        return new BaseFootballContext("FootballContext");
    }
}