매우 간단한 방법 :linq 테이블을 매개 변수로 사용하는 방법은 무엇입니까? 예를 들어
private int GetCount(ITable table) {
return (from T in table select T).Count();
}
매우 간단한 방법 :linq 테이블을 매개 변수로 사용하는 방법은 무엇입니까? 예를 들어
private int GetCount(ITable table) {
return (from T in table select T).Count();
}
:
은 PKID인가요 (된 IQueryable 테이블, intID를 INT)? 대답은 0이나 1이 아니어야합니까? 어쨌든 ...개인 INT GetCount
Expression
을 동적으로 빌드해야합니다. 같은 뭔가 (테스트되지 않은,
based on this) :
static TEntity GetCount<TEntity>(this DataContext ctx, int key) where TEntity : class
{
return GetCount<TEntity, int>(ctx, key);
}
static TEntity GetCount<TEntity, TKey>(this DataContext ctx, TKey key) where TEntity : class
{
var table = ctx.GetTable<TEntity>();
var pkProp = (from member in ctx.Mapping.GetMetaType(typeof(TEntity)).DataMembers
where member.IsPrimaryKey
select member.Member).Single();
ParameterExpression param = Expression.Parameter(typeof(TEntity), "x");
MemberExpression memberExp;
switch (pkProp.MemberType)
{
case MemberTypes.Field: memberExp = Expression.Field(param, (FieldInfo)pkProp); break;
case MemberTypes.Property: memberExp = Expression.Property(param, (PropertyInfo)pkProp); break;
default: throw new NotSupportedException("Invalid primary key member: " + pkProp.Name);
}
Expression body = Expression.Equal(
memberExp, Expression.Constant(key, typeof(TKey)));
var predicate = Expression.Lambda<Func<TEntity, bool>>(body, param);
return table.Count(predicate);
}
당신이 뭔가를 의미?
private int GetCount<T>(IQueryable<T> table) {
// return (from T in table select T).Count();
return table.Count();
}
그런데 Count()
을 직접 호출하지 않는 이유는 무엇입니까? 귀하의 코멘트를 다시
우수. 하지만 where 절을 어떻게 사용할 수 있습니까? private int GetCount
그래, 작동하지만 람다 식을 직접 사용하면된다.'table.Where (row => row.Id == id) .Count()' –
나는 row.id에 접근 할 수 없다. –
Linq는 당신이 응용 프로그램을 안전하고 주위 쿼리를 전달할 수 실제로 데이터 base.This 방법에 대한 쿼리를 전송하지 않고 쿼리를 확장하기 위해 우리가 할 수 놀라운 된 IQueryable 인터페이스를 포함 사운드 및 실제로 실제 데이터가 필요한 모든 클래스는 실제 쿼리를 db에 보냅니다. 예를 들어 모든 사용자의 쿼리 반환하는 방법이 있습니다
public IQueryable<User> GetAll()
{
return from user in dbContext.Users select user;
}
을하고 avtive 사용자를 얻으려면 only.here 당신이) (위의 예제 목록에서 방법을
foreach(var activeUser in (from user in UserRepository.GetAll() where user.Active==true select user).List())
{
//do something;
}
을 수행 할 수있는 작업 Linq가 데이터베이스에 쿼리를 보낼 것이다.
좋은 해결책을 주셔서 감사합니다. –