-1
在WebApi Core中,我通过AddDataAccess将上下文传递给服务集合。我真的不明白为什么上下文是在该行空:从泛型类到泛型基类的值
var res = this.Context.Set<TEntity>().AsEnumerable();
有人会说,因为在构造函数中的参数,但我它的正确有空。应该是别的东西。
//在Stratup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<myConnectionStringContext>
(options => options.UseSqlServer(_config["ConnectionStrings:myConnectionString"]));
services.AddDataAccess<myConnectionStringContext>();
// Add framework services.
services.AddMvc();
}
//在我的personnal包
public static class ServiceCollectionExtentions
{
public static IServiceCollection AddDataAccess<TEntityContext>(this IServiceCollection services)
where TEntityContext : DbContext
{
RegisterDataAccess<TEntityContext>(services);
return services;
}
private static void RegisterDataAccess<TEntityContext>(IServiceCollection services)
where TEntityContext : DbContext
{
services.AddTransient(typeof(TEntityContext));
services.AddTransient(typeof(IRepository<>), typeof(GenericEntityRepository<>));
}
}
public class EntityBase
{
[Key]
public int Id { get; set; }
}
public interface IRepository<TEntity>
{
IEnumerable<TEntity> GetAll();
}
public class GenericEntityRepository<TEntity> : EntityRepositoryBase<DbContext, TEntity>
where TEntity : EntityBase, new()
{
public GenericEntityRepository() : base(null)
{ }
}
public abstract class EntityRepositoryBase<TContext, TEntity> : RepositoryBase<TContext>, IRepository<TEntity>
where TContext : DbContext where TEntity : EntityBase, new()
{
protected EntityRepositoryBase(TContext context) : base(context)
{ }
public virtual IEnumerable<TEntity> GetAll()
{
return this.Context.Set<TEntity>().AsEnumerable();
}
}
public abstract class RepositoryBase<TContext> where TContext : DbContext
{
protected TContext Context { get; private set; }
protected RepositoryBase(TContext context)
{
this.Context = context;
}
}
您没有阅读。我期待这个答案,但我不认为是这样。如果这是如何传递DbContext呢? –
@ Kris-I我已经更新了我的答案,向你展示了为什么这是真的。 – Svek
好了解。但是,如何创建DBContext呢? (带新) –