通用LINQ TO SQL查询 [英] Generic LINQ TO SQL Query
问题描述
可以说我有两个由设计者生成的L2S类,其中一个属性如下:
public class A
{
public bool IsActive {get; set;}
}
public class B
{
public bool IsActive {get; set;}
}
我有一个通用的DataAccess类,如下所示:
public class DataAccessBase< T>其中T:class
{
NWDataContext dataContext = new NWDataContext();
公共IList< T> GetAllActive()
{
return dataContext.GetTable< T>()
.where(T.IsActive == true)----->我该如何做这样的事情?
.ToList< T>();
$ / code>
现在从GetAllActive()如何返回所有A或B类型的活动对象。我的猜测是,我必须使用反射来做到这一点,但我对反射非常陌生。任何人都可以指向正确的方向吗?
您需要传递给 Enumerable.Where
是 Predicate< T>
。 Predicate< T>
是一个委托,它可以吃掉 T
的实例并返回一个bool;您可以将谓词想象为代表 true
或 false
关于Ť
。
现在有一个更大的问题,就是除非你对 T
施加约束,编译器没有知道 T
具有名为 IsActive
的公共可读属性的方法。因此,你必须定义一个接口(或者一个基类)来实现(或者派生自 B
),并告诉 GetAllActive
这个接口(或基类)的实现(或派生自)的方法。您可以通过在 DataAccessBase
的定义中限制 T
来实现。因此:
interface IIsActive {
bool IsActive {get;组; }
}
class A:IIsActive {
public bool IsActive {get;组; }
}
class B:IIsActive {
public bool IsActive {get;组; }
}
public class DataAccessBase< T>其中T:class,IIsActive {
public IList< T> GetAllActive(){
return dataContext.GetTable< T>()
.Where(x => x.IsActive)
.ToList();
}
}
Lets say I have two L2S classes generated by the designer with one property as follows:
public class A
{
public bool IsActive {get;set;}
}
public class B
{
public bool IsActive {get;set;}
}
I have a generic DataAccess class as follows:
public class DataAccessBase<T> where T : class
{
NWDataContext dataContext = new NWDataContext();
public IList<T> GetAllActive()
{
return dataContext.GetTable<T>()
.where(T.IsActive == true) -----> How can i do something like this?
.ToList<T>();
}
}
Now from the GetAllActive() how can I return all active objects of either A or B type. My guess is that I have to use reflection to do this but I am very new to reflection. Can anyone point me in the right direction?
What you need to pass to Enumerable.Where
is a Predicate<T>
. A Predicate<T>
is a delegate that can eat instances of T
and return a bool; you can think of a predicate as representing a property that is either true
or false
about instaces of T
.
Now, there is a larger issue which is that unless you put a constraint on T
, the compiler has no way of knowing that T
has a publicly readable property named IsActive
. Thus, you have to define an interface (or a base class) that both A
and B
implement (or derive from) and tell the method GetAllActive
that T
implements (or derives from) this interface (or base class). You can do this by constraining T
in the definition of DataAccessBase
. Thus:
interface IIsActive {
bool IsActive { get; set; }
}
class A : IIsActive {
public bool IsActive { get; set; }
}
class B : IIsActive {
public bool IsActive { get; set; }
}
public class DataAccessBase<T> where T : class, IIsActive {
public IList<T> GetAllActive() {
return dataContext.GetTable<T>()
.Where(x => x.IsActive)
.ToList();
}
}
这篇关于通用LINQ TO SQL查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!