[英]Object to IQueryable
An API I'm writing always needs an IQueryable as return type, even if it is a single object. 我正在编写的API总是需要IQueryable作为返回类型,即使它是单个对象。 This is imposed, I cannot change this. 这是强加的,我无法改变这一点。 How would I go about creating an IQueryable from an object. 我如何从一个对象创建一个IQueryable。
The code I have now feels wrong to me. 我现在的代码对我来说是错的。
List<Entity> listOfEntity = new List<Entity>();
listOfEntity.Add(entity);
IQueryable<Entity> queryableEntity = listOfEntity.AsQueryable();
EDIT: like kienct89 I created a generic extension method for easier use: 编辑:像kienct89我创建了一个通用的扩展方法,以方便使用:
public static class ObjectExtensionMethods
{
public static IQueryable<T> ToQueryable<T>(this T instance)
{
return new [] {instance}.AsQueryable();
}
}
The method can be used simply calling it on the object you created: 该方法可以简单地在您创建的对象上调用它:
object anObject = new object();
anObject.ToQueryable();
@kienct89: Wow that is almost exactly what I did, even the names match, I just took array because it seemed less expensive, you did it in one line: @ kienct89:哇,这几乎就是我所做的,即使名字匹配,我只是拿了数组,因为它似乎更便宜,你在一行中做到了:
public static class ObjectExtensionMethods { public static IQueryable<T> ToQueryable<T>(this T instance) { TEntityType[] arrayOfObject = {instance}; return arrayOfObject.AsQueryable(); } }
With both our answers I changed it to: 我们的答案都改为:
public static class ObjectExtensionMethods { public static IQueryable<T> ToQueryable<T>(this T instance) { return new [] {instance}.AsQueryable(); } }
I don't know why you need to return IQueryable
, but I think it's better to create an extension class to convert object to IQueryable
. 我不知道为什么你需要返回IQueryable
,但我认为最好创建一个扩展类来将对象转换为IQueryable
。 That would help to achieve 3 things 这将有助于实现3件事
Assuming you have 3 model classes 假设你有3个模型类
public class Entity
{
public int Id {get; set;}
}
public class Customer : Entity
{
public string Name {get; set;}
}
public class Cart : Entity
{
}
We can write extension class like this 我们可以像这样编写扩展类
public static class QueryableExtension
{
public static IQueryable<T> ToQueryable<T>(this T obj) where T : Entity
{
return new List<T> { obj }.AsQueryable();
}
}
How to use 如何使用
var customer = new Customer { Id = 1, Name = "test" };
var cart = new Cart { Id = 1 };
IQueryable<Customer> customers = customer.ToQueryable();
IQueryable<Cart> carts = cart.ToQueryable();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.