简体   繁体   中英

EF5: Load only related records, that are not deleted (IsDeleted = false)

I am using EF5 Code First with self-tracking entities. How can I ensure, that only the related Product nodes of my Category entity are loaded, that are IsDeleted == false ? I created the Model using the EF Power Tools and would like to store this extra query condition somewhere in the model mapping classes (in MyContext : DbContext or ProductMap : EntityTypeConfiguration<Product> ). Every time I access the Products attribute of the Category class, only the products that are not deleted should be loaded. Thanks for your help!

In your context you can add a method which returns your query:

public class MyContext: DbContext
{
    public DbSet<Entity> Entities {get;set;}

    public IQueryable<Entity> NonDeletedEntities()
    {
        return this.Entities.Where(e => e.IsDeleted == false);
    }
}

Now you can consume that query and aggregate it with other conditions and they will both be queried

new MyContext().NonDeletedEntities().Where(e => e.Name == "Philippe");

//is the same as
new MyContext().Entities.Where(e => e.IsDeleted == false && e.Name == "Philippe");

UPDATE

As noted in your comment, If you want to access non-deleted products from the category entity

public class Category 
{
    public virtual ICollection<Product> Products { get; set; }
    public IQueryable<Products> NonDeletedProductts() 
    {
        return this.Products.Where(e => e.IsDeleted == false);
    }
}

I have not tested this, but it should work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM