简体   繁体   中英

Cast from interface to specific class with DbSet

Let's say I've the following code:

public interface IInterface
{
    string Name { get; set; }
}

public class Foo : IInterface
{
    public string Name { get; set; }
}

public class Bar : IInterface
{
    public string Name { get; set; }
}

///

public class Service
{
    private List<Foo> MyList();
    public IQueryable<Foo> GetObjects()
    {
        return MyList().AsQueryable();
    }

    public IQueryable<Bar> GetObjectsFromBD()
    {
        return Entities.Bar;
    }
}

And here's how I'll use it

public IQueryable<IInterface> GetFooBars()
{
    var foobars = new IQueryable<IInterface>();
    if(someStuff)
        foobars = service.GetObjects(); /*From cache*/
    else
        foobars = service.GetObjectsFromBD(); /*From DbSet*/
    return foobars;
}

For some reason, I want to do specific treatment later if the source is the DB or not. So I try to cast as Foo

var query = GetFooBars();
var casted = query as IQueryable<Foo>;
if(casted == null) /*Coming from DB*/
    /*Some conditions*/
else /*Coming from cache*/
    /*Some other conditions*/

But for some reason that I ignore casted is always null, no matter if it comes from the DB or not.

If I try do debug with some query.GetType() , it yields

 System.Data.Entity.Infrastructure.DbQuery`1[MyNamespace.IInterface]

What did I miss? How can I achieve what I want to do without enumerate the query?

First problem: to check if the query is coming from the database, you need to check against DbQuery , not IQueryable (since both methods return a IQueryable , but only the database method returns a DbQuery ):

var query = GetFooBars();
var casted = query as DbQuery<Foo>;
if(casted == null) // *not* from database!

Second problem: your method doesn't return a DbQuery<Foo> or even a IQueryable<Foo> - it returns a IQueryable<IInterface> . While your collection is actually a collection of Foo s, the type system doesn't know that. So the correct code would be:

var query = GetFooBars();
var casted = query as DbQuery<IInterface>;
if(casted == null) //...

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