Csharp/C#教程:Linq 2 SQL – Generic where子句分享


Linq 2 SQL – Generic where子句

有没有办法做到这一点

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

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

(已删除的属性绑定方法)

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

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

您需要创建实体派生的适当接口(除非您想使用Marc的示例表达式树):

 public interface IIdentifiedEntity { int Id { get; } // Set as well? Depends on your situation. } 

然后你可以写:

 public T GetItemById(int id) where T : class, IIdentifiedEntity { Table table = _db.GetTable(); return table.Where(t => t.Id == id) .Single(); } 

也许你可以在Generic Predicates下找到一些东西, url是https://www.albahari.com/nutshell/predicatebuilder.aspx 。 这是页面的最后一部分。

 var X = _db.table.Select(i => i.Id == id); 

这将返回IQueryable

上述就是C#学习教程:Linq 2 SQL – Generic where子句分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/955915.html

(0)
上一篇 2021年11月21日
下一篇 2021年11月21日

精彩推荐