Entity Framework conditional mapping with code first?

十年热恋 提交于 2019-12-02 17:51:03

问题


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?


回答1:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!