私は以下のようにIUnitOfWorkを暗示するDbContextを持っています
public interface IUnitOfWork {
IDbSet<TEntity> Set<TEntity>() where TEntity : class;
int SaveChanges();
}
また、以下のように、すべてのエンティティに1つのインターフェイスとすべてのエンティティに1つのインペンションがあります
public interface IRayanService<T> : where T : class {
void Add(T entity);
void Delete(T entity);
T Find(Func<T, bool> predicate);
IList<TResult> GetAll<TResult>(Func<T, bool> predicate, Func<T, TResult> selector);
IList<T> GetAll(Func<T, bool> predicate);
int GetAllCount(Func<T, bool> predicate);
}
とその実装
public class RayanService<TEntity> : IRayanService<TEntity>
where TEntity : class {
protected IUnitOfWork _uow;
protected IDbSet<TEntity> _tEntities;
public RayanService(IUnitOfWork uow) {
_uow = uow;
_tEntities = _uow.Set<TEntity>();
}
public virtual void Add(TEntity entity) {
_tEntities.Add(entity);
}
public void Delete(TEntity entity) {
_tEntities.Remove(entity);
}
public TEntity Find(Func<TEntity, bool> predicate) {
return _tEntities.Where(predicate).FirstOrDefault();
}
public IList<TEntity> GetAll(Func<TEntity, bool> predicate) {
return _tEntities.Where(predicate).ToList();
}
public IList<TResult> GetAll<TResult>(Func<TEntity, bool> predicate, Func<TEntity, TResult> selector) {
return _tEntities.Where(predicate).Select(selector).ToList();
}
//when using this we get select * from entity!
public virtual int GetAllCount(Func<TEntity, bool> predicate) {
return _tEntities.Count(predicate);
}
}
これがクラスの1つです
public interface IPollService : IRayanService<Poll> {
}
public class PollService : RayanService<Poll>, IPollService {
public PollService(IUnitOfWork uow)
: base(uow) {
}
public override int GetAllCount(Func<Poll, bool> predicate) {
// genrates select count(*)
int result = _tEntities.Where(x => true).Count();
// genrates select *
result = _tEntities.Where(predicate).Count();
// genrates select count(*)
var ttt = _tEntities.Select(x => x.ID);
result = ttt.Where(x => true).Count();
// genrates select *
var yyy = _tEntities.Where(predicate);
var zzz = yyy.Select(x=>x.ID);
result = yyy.Select(x => x.ID).Count();
result = zzz.Count();
// genrates select count(*)
result = _tEntities.Count();
// genrates select *
result = _tEntities.Count(predicate);
// genrates select count(*)
result = _tEntities.Count(x=>true);
return result;
}
}
問題は、私が次のようなコードを使用する場合です
public IPollService ipolls { get; set; }
public void Test {
int countrecords = ipolls.GetAllCount(x=>true);
}
SQLServerでは取得でき
select * from Entity where predicate
ませんselect count(*) from entity where predicate
だから私は含意を変更し、オーバーライドされた関数を追加PollService
し、コードでコメントされた結果を取得します。何が起こっているのか理解できません。
直接使用するFunc<Poll, bool>
と望ましい結果が得られるようですが、送信された引数からその値を使用すると、望ましくない結果が得られます
その他の注意事項:使用しますasp.net Web Forms
。EF Code First
バージョンは5.0で、開発ツールはですvs2012
。DIの場合も使用します。StructureMap