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?
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;
}
}
}
来源:https://stackoverflow.com/questions/8161689/entity-framework-conditional-mapping-with-code-first