Я попытался выполнить общую контекстную практику в EF my. Код указан нижеКак использовать общий контекст в EF
// Base class of all context
public class DbContextBase<TContext> : DbContext, IDbContext where TContext : DbContext
{
public DbContextBase() :
base("DataConnection")
{
Configuration.LazyLoadingEnabled = false;
}
static DbContextBase()
{
Database.SetInitializer<TContext>(null);
}
public new IDbSet<T> Set<T>() where T : class
{
return base.Set<T>();
}
}
// My one splitted context
public class SecurityDbContext : DbContextBase<SecurityDbContext>
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new MenivaModuleConfiguration());
modelBuilder.Configurations.Add(new ModuleItemConfiguration());
modelBuilder.Configurations.Add(new ItemControllerConfiguration());
modelBuilder.Configurations.Add(new PermissionListConfiguration());
modelBuilder.Configurations.Add(new CustomRoleConfiguration());
base.OnModelCreating(modelBuilder);
}
}
// IDbInterface implimented by all splited context
public interface IDbContext
{
IDbSet<T> Set<T>() where T : class;
int SaveChanges();
DbEntityEntry Entry(object o);
void Dispose();
}
// constructor of my unit work; my unit of work class detentions few things removed (dispose)
public UnitOfWork(IDbContext dbContext)
{
_context = dbContext;
}
// I am using activator pattern to get corresponding repositories its the code is given below .
public IRepository<T> Repository<T>() where T : class
{
if (_repositories == null)
_repositories = new Hashtable();
var type = typeof(T).Name;
if (!_repositories.ContainsKey(type))
{
var repositoryType = typeof(BaseRepository<>);
var repositoryInstance =
Activator.CreateInstance(repositoryType
.MakeGenericType(typeof(T)), _context);
_repositories.Add(type, repositoryInstance);
}
return (IRepository<T>)_repositories[type];
}
// Unit of work save
public void Save()
{
_context.SaveChanges();
}
// This is my Base repository generic repository
public class BaseRepository<TEntity> : IRepository<TEntity> where TEntity : class
{
IDbContext Context;
IDbSet<TEntity> DbSet;
public BaseRepository(IDbContext context)
{
Context = context;
DbSet = context.Set<TEntity>();
}
#region Implementation of IRepository<TEntity>
public TEntity FindById(object id)
{
return DbSet.Find(id);
}
public void Add(TEntity entity)
{
DbSet.Add(entity);
}
public void Update(TEntity entity)
{
Context.Entry(entity).State = EntityState.Modified;
DbSet.Attach(entity);
}
public void Delete(TEntity entity)
{
Context.Entry(entity).State=EntityState.Deleted;
DbSet.Remove(entity);
}
public IQueryable<TEntity> GetAll()
{
return DbSet;
}
public IQueryable<TEntity> Query(CompositeSpecification<TEntity> specification)
{
return DbSet.Where(specification.IsSatisfiedBy).AsQueryable();
}
#endregion
}
Уверен, что связь между Ef и sql установлена. и у меня есть данные в моей базе данных. но findbyId всегда показывает ошибку «No sequence found». я проверил и нашел, что ef не будет заполнять dbSet. любое предложение
Последовательность не содержит соответствующий элемент нет какого-либо дополнительного внутреннего исключение EF 6.0.2
Извините, но задал этот вопрос. приведенные выше коды работают хорошо, но мой файл сопоставления (конфигурация) содержит столбец errorType (nvarchar, введенный в narchar). потратил в аренду еще 13 часов и 2 ГБ или более данных. –