C# 可以查询接口属性吗?
我有以下课程:C# 可以查询接口属性吗?,c#,entity-framework,entity-framework-5,C#,Entity Framework,Entity Framework 5,我有以下课程: public class BicycleSellerListing : IUserName { public UserProfile UserProfile { get; set; } /// <summary> /// IUserName interface property /// </summary> public string UserName { get {
public class BicycleSellerListing : IUserName
{
public UserProfile UserProfile { get; set; }
/// <summary>
/// IUserName interface property
/// </summary>
public string UserName
{
get
{
return UserProfile.UserName;
}
}
}
此查询:
public static List<T> GetList<T>(string userName) where T : class, IUserName
{
using (SqlUnitOfWork work = new SqlUnitOfWork())
{
return work.GetList<T>(row => row.UserName == userName)
.ToList();
}
}
publicstaticlist-GetList(字符串用户名),其中T:class,IUserName
{
使用(SqlUnitOfWork=new SqlUnitOfWork())
{
return work.GetList(row=>row.UserName==UserName)
.ToList();
}
}
当我执行此查询时,我得到以下异常:
LINQ to中不支持指定的类型成员“UserName”
实体。仅初始值设定项、实体成员和实体导航
支持属性
我理解为什么会出现异常,但我想知道是否有一种方法可以使用该界面执行此查询?回答您的问题: 对。没问题。您遇到的故障不是因为接口 问题是,您无法查询不具有Linq 2实体的mappe的属性 我也有这个问题 基础expressionbuilder无法区分映射到数据库的属性和未映射到数据库的属性 这是个问题,因为编译器帮不了你。 在Linq to对象中,这没有问题,因此编译器不会抛出任何错误/警告
您应该尝试澄清此属性未映射-可能是通过前缀或包含所有“自定义”属性的嵌套类映射的。除了现有的答案外,您还可以在内存中执行where,但这意味着检索整个表 通常我不会推荐这个
public static List<T> GetList<T>(string userName) where T : class, IUserName
{
using (SqlUnitOfWork work = new SqlUnitOfWork())
{
return work.GetList<T>()
.AsEnumerable()
.Where(row => row.UserName == userName)
.ToList();
}
}
publicstaticlist-GetList(字符串用户名),其中T:class,IUserName
{
使用(SqlUnitOfWork=new SqlUnitOfWork())
{
return work.GetList()
.可计算的()
.Where(row=>row.UserName==UserName)
.ToList();
}
}
一些解决方法:
- 您可以尝试在运行时和
然后动态编译并调用执行查询的泛型方法 用这种类型 - 可以在运行时使用 表达式类
- 您可以尝试使用实体SQL查询语法而不是Linq
实体成员
<代码>用户名不是模型的一部分,因此不是实体成员
。我想我可以。我必须回到办公桌上进行测试。我要强调的是,这将检索整个表。根据此表的大小,这可能是一个巨大的性能损失。
Is it possible to query on an interface property?
public static List<T> GetList<T>(string userName) where T : class, IUserName
{
using (SqlUnitOfWork work = new SqlUnitOfWork())
{
return work.GetList<T>()
.AsEnumerable()
.Where(row => row.UserName == userName)
.ToList();
}
}