gpt4 book ai didi

c# - Linq 2 SQL - 通用 where 子句

转载 作者:太空狗 更新时间:2023-10-29 23:12:00 25 4
gpt4 key购买 nike

有没有办法做到这一点

public T GetItemById(int id)
{
Table<T> table = _db.GetTable<T>();
table.Where(t => t.Id == id);
}

注意 i.Id 在上下文中不存在,因为 linq 不知道它正在使用什么对象,而 Id 是表的主键

最佳答案

(删除了绑定(bind)到属性的方法)

编辑:这是元模型方式(因此它适用于映射文件和属性对象):

static TEntity Get<TEntity>(this DataContext ctx, int key) where TEntity : class
{
return Get<TEntity, int>(ctx, key);
}
static TEntity Get<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.Single(predicate);
}

关于c# - Linq 2 SQL - 通用 where 子句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/637672/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com