我正在尝试使用EF6创建一个小型数据访问框架。 在所有示例中,我得到了数据库中表的存储库类。
例如:ProductRepository.cs,CustomerRepository.cs等。
但是,我想让它变得通用
我的bdcontext是
public class EFDbContext<T> : DbContext where T : class
{
public DbSet<T> Entity { get; set; }
}
和IRepository接口
public interface IRepository<TEntity> where TEntity : class
{
List<TEntity> FetchAll();
IQueryable<TEntity> Query { get; }
void Add(TEntity entity);
void Delete(TEntity entity);
void Save();
}
和SqlRepository类
public class SqlRepository<T> : IRepository<T> where T : class
{
EFDbContext<T> db;
public SqlRepository(EFDbContext<T> db)
{
this.db = db;
}
public IQueryable<T> Query
{
get { return db.Entity; }
}
public List<T> FetchAll()
{
return Query.ToList();
}
public void Add(T entity)
{
db.Entity.Add(entity);
}
public void Delete(T entity)
{
db.Entity.Remove(entity);
}
public void Save()
{
db.SaveChanges();
}
}
但它无法正常工作。
我使用了两个实体:
public class Product
{
public int ProductID { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string Category { set; get; }
public decimal Price { get; set; }
public decimal test { get; set; }
}
public class Customer
{
public int CustomerID { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string Category { set; get; }
public decimal Price { get; set; }
public decimal test { get; set; }
}
但是当我使用EF6的代码优先功能时,它创建两个名为customer和product的数据库而不是同一个数据库中的两个表
我的代码中有任何错误吗? 我是EF的新手,
请帮助..
谢谢
答案 0 :(得分:2)
您不需要通用上下文。上下文是对数据库的抽象;你不想要它的多个不同版本。
您的通用存储库方法很好。
将您的DbContext更改为非通用,并让您的通用存储库引用DbContext。