views:

91

answers:

2

How can I use cast in Linq to Entities?

I need something like this:

if (typeof(myObject) is IMyInterface)
{
  return MyObjectSet.Where(x => ((IMyInterface)x).MyProperty == 1);
}

If I try above code, I get an exception. It's an expected behavior of EF or it's a bug?

A: 

Instead of casting, you might want to use the OfType extension method:

return MyObjectSet.OfType<IMyInterface>().Where(x => x.MyProperty == 1);
JoeGaggler
Don't think that will work, "OfType<TResultType> method can only be applied to an ObjectQuery<T> of an entity type or complex type that is defined in the EDM." ref: http://msdn.microsoft.com/en-us/library/bb301729.aspx
Simon Fox
Error 1 Cannot implicitly convert type 'System.Linq.IQueryable<IMyInterface>' to 'System.Linq.IQueryable<T>'. An explicit conversion exists (are you missing a cast?)
Zote
A: 

This is expected. Since your interface is not in your EDMX, the EF doesn't know how to map it in an L2E query. Hard to give a good workaround without really knowing what problem you're trying to solve.

Craig Stuntz
It's an multi-client database. Some data will be shared to all clients. And others will be private only for 1 client.I'm planning to implement an interface that tell to repository that this class is private, and repository will "attach" an filter.With this, I'll remove developer error and we'll just need to implement this interface.Sorry my poor english.
Zote
That will be hard to do well. You may limit the results returned from your repository, but if they have navigation/association properties, a client may be able to follow them to "private" data. I don't think there's a "generic" solution to this. I think that privacy concerns need to be addressed carefully and on a case-by-case basis. Putting private data in a DB is always challenging to do well.
Craig Stuntz