I have an entity that I need to return only records where a given field value is greater than zero. I have seen examples of conditional mapping in the edmx and that seems like what I am in need of. However, my project is in EF 4.1 code first. Is there not a way to do this using the code first approach?
Asked
Active
Viewed 2,388 times
1 Answers
5
I dont think there is an inbuilt method for achieving this, you can however expose a property in your DbContext in which you apply filtering, initially this will be readonly but i dont see a reason why you shouldnt be able to create your own DbSet implementation reflecting back to another DbSet (ProxyDbSet)
Readonly example:
class MyDbContext : DbContext
{
public IDbSet<User> Users { get; set; }
public IQueryable<User> Admins
{
get
{
return from user in users
where user.Role == "admin"
select user;
}
}
}

Polity
- 14,734
- 2
- 40
- 40
-
Thank you @Polity. If i understand correctly, this would result in EF returning my entire recordset and then assigning the linq-filtered set to the, in your example, Admins IQuaryable property. I was hoping not to do this as the entire set will be quite large. However, from what I can tell, this may be the best solution. Thanks so much for the quick reply! – RockyMountainHigh Nov 17 '11 at 04:00
-
2@RockyMountainHigh - No it wont actually, Note that DbSet implements IQueryable as well as the method itself returning IQueryable. This means that Calling admin wont return anything but a definition of a query. As soon as you start doing a foreach over the result of Admins, a SQL query will be generated including a where filter on the role of users. Therefore, this is just as efficient as conditional mapping – Polity Nov 17 '11 at 04:03
-
Perfect! Thank you! Learn something new today? Check! – RockyMountainHigh Nov 17 '11 at 04:14