Entity Framework 4.1 - Override Entity (DBSet) with Filter

后端 未结 5 1676
余生分开走
余生分开走 2021-02-06 03:38

I\'m trying to do something which should be relatively easy, but i just dont know how to construct it.

I have a Generated Entity which I\'d like to override by adding a

相关标签:
5条回答
  • 2021-02-06 04:08
    public override DbSet<Assignee> Assignees 
    {
        get
        {
            return base.Assignees.Where(z => z.IsActive == true);
        }
        set; 
    }
    

    This what you want?

    0 讨论(0)
  • 2021-02-06 04:11

    Try exposing DbSet<Assignee> and IQueryable<Assignee> with different names

    public partial class MyEntities: DbContext
    {
        public MyEntities()
            : base("name=MyEntities")
        {
        }
    
        public DbSet<Assignee> AssigneesSet { get; set; }
    
        public IQueryable<Assignee> Assignees 
        {
            get
            {
                return AssigneesSet.Where(z => z.IsActive == true);
            }
        }
    }
    
    0 讨论(0)
  • 2021-02-06 04:17

    A good practice is to create repository classes in a DAL folder(use the name you want). Then do the filters there. Here is a microsoft tutorial for that:

    http://www.asp.net/mvc/tutorials/getting-started-with-ef-5-using-mvc-4/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application

    Depending of the condition you want is not possible to put on EF mapping condition, here is the reason: http://entityframework.codeplex.com/workitem/48

    0 讨论(0)
  • 2021-02-06 04:19

    I know this is super old, but another simple and elegant way, without changing any existing names, is using the new keyword to hide the original member, like this:

    public new IQueryable<Assignee> Assignees 
    {
        get
        {
            return base.Assignees.Where(z => z.IsActive == true);
        }
    }
    

    Just wanted to share for any future visitors, hope it helps!

    0 讨论(0)
  • 2021-02-06 04:20

    Have you tried adding a Condition to the Table Mapping in your model? Right click the entity in your edmx and choose "Table Mapping". Then "Add a condition". Probably a more elegant solution.

    0 讨论(0)
提交回复
热议问题