Я слежу за этой статьей в MSDN. Я перенес ее на EF Code First.
public interface IUnitOfWork
{
IRepository Employees { get; }
IRepository TimeCards { get; }
void Commit();
}
public class HrContext : DbContext
{
public DbSet Employees { get; set; }
public DbSet TimeCards { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity()
.HasMany(e => e.TimeCards)
.WithOptional(tc => tc.Employee);
}
}
public class SqlRepository : IRepository
where T : class
{
private readonly DbSet entitySet;
public SqlRepository(DbContext context)
{
this.entitySet = context.Set();
}
public void Add(T newEntity)
{
this.entitySet.Add(newEntity);
}
public IQueryable FindAll()
{
return this.entitySet;
}
public T FindById(params object[] keys)
{
return this.entitySet.Find(keys);
}
public IQueryable FindWhere(Expression> predicate)
{
return this.entitySet.Where(predicate);
}
public void Remove(T entity)
{
this.entitySet.Remove(entity);
}
}
public class SqlUnitOfWork : IUnitOfWork, IDisposable
{
private readonly HrContext context;
private IRepository employees;
private IRepository timeCards;
public SqlUnitOfWork()
{
this.context = new HrContext();
}
public IRepository Employees
{
get
{
return new SqlRepository(context);
}
}
public IRepository TimeCards
{
get
{
return new SqlRepository(context);
}
}
public void Commit()
{
this.context.SaveChanges();
}
public void Dispose()
{
context.Dispose();
}
}
var query = from e in unitOfWork.Employees.FindAll()
from tc in unitOfWork.TimeCards.FindAll()
where tc.Employee.Id == e.Id && e.Name.StartsWith("C")
select tc;
var timeCards = query.ToList();
Эта модель великолепна, поскольку дает мне возможность тестирования. Однако выполнение запросов, подобных приведенному выше, вызывает эту
LINQ to Entities does not recognize the method
'System.Linq.IQueryable`1[DomainModel.Models.TimeCard] FindAll()'
method, and this method cannot be translated into a store expression.
Я понимаю ошибку, но есть ли способ избежать ее, но все же сохранить репозитории для проверки?