简体   繁体   中英

Object to IQueryable

An API I'm writing always needs an IQueryable as return type, even if it is a single object. This is imposed, I cannot change this. How would I go about creating an IQueryable from an object.

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:

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:

 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 . That would help to achieve 3 things

  1. Easier to update the code in future since you only have to manage the conversion logic in 1 file
  2. Less duplicated codes ==> less bugs
  3. Easier to test

Assuming you have 3 model classes

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM