RockyMountainHigh
RockyMountainHigh

Reputation: 3021

Entity Framework conditional mapping with code first?

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?

Upvotes: 0

Views: 2403

Answers (1)

Polity
Polity

Reputation: 15130

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;
        }
    }
}

Upvotes: 5

Related Questions