Linq关于通用对象属性 [英] Linq on generic object property

查看:76
本文介绍了Linq关于通用对象属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好

public T GetbyId(int id)
{
            
      return connection.Table<T>().FirstOrDefault(x => x.Id == id);
}

我在x.id上收到错误!

i get error on the x.id!

错误 CS1061
'T'确实不包含'Id'的定义且没有扩展方法'Id'可以找到接受类型'T'的第一个参数(你是否缺少using指令或汇编引用?)

Error CS1061 'T' does not contain a definition for 'Id' and no extension method 'Id' accepting a first argument of type 'T' could be found (are you missing a using directive or an assembly reference?)

那么如何linq呢?

推荐答案

这是正确的。 T可能是一个没有Id属性的对象。如果你想要T具有这个属性,那么你需要在T上设置一个约束,使它实现一个具有该属性的接口,或者从一个类型派生出来。

That is correct. T is probably an object which doesn't have an Id property. If you want to require that T have this property then you need to put a constraint on T such that it implements an interface that has that property or derives from a type that does.

public interface IIdentifable
{
   int Id { get; }
}

public T GetbyId<T> ( int id ) where T: IIdentifable
{
   return connection.Table<T>().FirstOrDefault(x => x.Id == id);
}

您没有提供表< T>的任何上下文返回,但我认为它不是EF或类似的东西。如果它是EF,那么EF已经有一个Find方法可以完全按照你想要的方式完成,而不需要Id属性。它已经知道了PK。
对于非EF,表达式可能是更好的路径。

You didn't provide any context of what Table<T> returns but I assume it isn't EF or something like that. If it is EF then EF already has a Find method that can do exactly what you want without the need for the Id property. It already knows about PKs. For non-EF an expression might be the better route.

public T GetbyId<T> ( Func<T, bool> finder )
{
   return connection.Table<T>().FirstOrDefault(x => finder(x));
}

//Usage
instance.GetbyId(x => x.Id == id);


这篇关于Linq关于通用对象属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆