【发布时间】:2018-07-29 04:16:52
【问题描述】:
在对 EF6 有一些经验(如 this)之后,我想尝试一下 EF Core,因为我读过一些文章并观看了一些视频,说它的性能大大优于 EF6。
所以,我用类制作了示例程序:
public interface IEntity
{
int Id { get; set; }
}
public class Employee : IEntity
{
public int Id { get; set; }
public string FirstName { get; set; }
public string Surname { get; set; }
}
然后我用通用存储库创建了一个存储库模式:
public interface IRepository<T> : IDisposable where T : IEntity
{
void Insert(T entity);
void Delete(T entity);
IQueryable<T> SearchFor(Expression<Func<T, bool>> predicate);
IQueryable<T> GetAll();
T GetById(int id);
void Update(T entity);
void BeginTransaction();
IDbContextTransaction Transaction { get; }
}
public class Repository<T> : IRepository<T> where T : class, IEntity
{
private RosterContext _context;
private IDbContextTransaction _transaction;
public Repository(bool wrapTransaction = false)
{
_context = new MyContext();
if (wrapTransaction)
{
_transaction = _context.Database.BeginTransaction();
}
}
public void Update(T entity)
{
_context.Set<T>().Update(entity);
_context.SaveChanges();
}
public void BeginTransaction()
{
if (_transaction == null)
_transaction = _context.Database.BeginTransaction();
}
public void Insert(T entity)
{
_context.Set<T>().Add(entity);
_context.SaveChanges();
}
public void Delete(T entity)
{
var toDelete = GetById(entity.Id);
_context.Set<T>().Remove(toDelete);
_context.SaveChanges();
}
public IQueryable<T> SearchFor(Expression<Func<T, bool>> predicate)
{
return _context.Set<T>().AsNoTracking().Where(predicate);
}
public IQueryable<T> GetAll()
{
return _context.Set<T>().AsNoTracking();
}
public T GetById(int id)
{
return _context.Set<T>().AsNoTracking().FirstOrDefault(x => x.Id == id);
}
public IDbContextTransaction Transaction => _transaction;
public void Dispose()
{
_transaction?.Dispose();
_context?.Dispose();
}
}
这是上下文:
public class MyContext : DbContext
{
public DbSet<Employee> Employees { get; set; }
public MyContext()
{
Database.Migrate();
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlite("Data Source=test.db");
}
}
如您所见,这是最简单的示例:一个表,一个实体,具有存储在 SQLite 中的 2 个属性。问题是,第一次查询需要将近 5 秒,数据库中有 10 行。下一个是即时的。
我在配备 SSD 驱动器和 i5 处理器的计算机上工作。
有什么问题?是 SQLite 吗?是Database.Migrate();(如果我评论这一行,它不会改变任何东西)?还是所有的性能改进都很糟糕?
【问题讨论】:
-
等效代码在 EF 6 上运行需要多长时间?
-
我明天会检查一下,但是 10 行 5 秒还是太长了
-
当提到数据库性能时,诸如读取和写入数据之类的任务才是真正重要的。在处理启动代码和数据库迁移时,结果可能会有很大差异,但不会对最终用户产生任何影响。对于
Debug与Release构建(用户永远不会看到前者),结果也会有很大差异。
标签: c# sqlite ef-core-2.0