Entity Framework 4.1 - Override Entity (DBSet) Using a Filter

I'm trying to do something that should be relatively easy, but I just don't know how to build it.

I have a generated entity that I would like to override by adding the Linq Where statement.

In this case, partial for the context:

public partial class MyEntities: DbContext { public MyEntities() : base("name=MyEntities") { } public DbSet<Assignee> Assignees { get; set; } } 

I created a new particle MyEntities and tried the following

 public override DbSet<Assignee> Assignees { get { return this.Assignees.Where(z => z.IsActive == true); } set; } 

but this causes an ambiguity error (which is obvious).

How can i do this?

thanks

+7
source share
5 answers

Try showing DbSet<Assignee> and IQueryable<Assignee> 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); } } } 
+10
source
 public override DbSet<Assignee> Assignees { get { return base.Assignees.Where(z => z.IsActive == true); } set; } 

Is this what you want?

+2
source

Have you tried to add a condition to display the table in your model? Right-click the object in your edmx and select "Table Mapping". Then "Add Condition". Perhaps a more elegant solution.

+2
source

It is good practice to create repository classes in the DAL folder (use the name you need). Then make the filters there. Here is a tutorial for Microsoft:

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 on which condition you want, it is not possible to include an EF display condition, here's why: http://entityframework.codeplex.com/workitem/48

0
source

I know this is super old, but another simple and elegant way, without changing any existing names, uses the new keyword to hide the original element, for example:

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

Just wanted to share for future visitors, hope this helps!

0
source

All Articles