我有一个 Linq 应用程序,我需要获得一个动态的 where 表达式。我使用类:
public class EntityColumnsField
{
public String ColumnName { get; set; }
public Type ColumnType { get; set; }
public bool IsPK { get; set; }
public String TableName { get; set; }
public Type TableType { get; set; }
}
我通过方法获取实体的列列表:
public static IEnumerable<EntityColumnsField> GetAllColumnsFromEntity(params EntityObject[] entities)
{
if (entities == null || entities.Count() == 0)
throw new ArgumentNullException("entity");
List<EntityColumnsField> ColumnList = new List<EntityColumnsField>();
foreach (var entity in entities)
{
ColumnList.AddRange(from p in entity.GetType().GetProperties()
where p.GetCustomAttributes(typeof(EdmScalarPropertyAttribute), false).Any()
select new EntityColumnsField()
{
TableName = entity.GetType().Name,
ColumnName = p.Name,
ColumnType = p.PropertyType,
IsPK = p.GetCustomAttributes(false).Where(a => a is EdmScalarPropertyAttribute && ((EdmScalarPropertyAttribute)a).EntityKeyProperty).Count() > 0
});
}
return ColumnList.OrderBy(a => a.TableName);
}
比我有 3 个表(User、UserPartner 和 UserFriends),我需要为所有字符串字段生成 where 条件。我尝试这样做:
using (var db = new DB())
{
var ll = from x in db.Users
join y in db.UserPartners on x.ID equals y.ID
join z in db.UserFriends on x.ID equals z.ID
select new { Users = x, UserPartners = y, UserFriends = z };
}
if (!String.IsNullOrEmpty(fulltext))
{
var AllSearchField = Utils.GetAllColumnsFromEntity(new User(), new UserPartner(), new UserFriends());
//TODO:
//Here i need a code, which generate predicate for all text fields in tables
//the result would be like :
//ll.Where(a => a.Users.Address.Contains(fulltext) || a.Users.Email.Contains(fulltext) || a.UserPartners.Email.Contains(m.FullText))
}
有谁知道如何做到这一点?谢谢