开发者

How can I have Entity Framework return related objects with some defaults?

开发者 https://www.devze.com 2023-03-25 06:29 出处:网络
Say I have Project and Task EF Code first classes public class Project { public int ID { ge开发者_高级运维t; set; }

Say I have Project and Task EF Code first classes

public class Project
    {
        public int ID { ge开发者_高级运维t; set; }
        public string Name { get; set; }
        public virtual ICollection<Task> Tasks { get; set; }
    }

    public class Task
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public int ProjectId { get; set; }
        public bool IsDeleted {get; set;}
        public virtual Project Project { get; set; }
    }

Say I have

public void SomeAction()
{
Project p= repository.GetById(1);
var tasks = p.Tasks;
//var tasks = p.Tasks.Where(t=>t.IsDeleted==false);
}

I would like that my Tasks property on the Project class will always perform that filter on IsDeleted and just return that subset ... to avoid having to write that condition all over the place...

Any recommendations?

Edit:

Im using EF Code First


Add a discriminator to your model in the OnModelCreating method

modelBuilder.Entity<TEntity>().Map(m => m.Requires("IsDeleted").HasValue(false));

Caveats

  • You can no longer load deleted items (unless you map IsDeleted true to another entity, then you may lose your automatic filtering)
  • The poco class cannot have the IsDeleted property (discriminators cannot be mapped)
  • because the IsDeleted cannot be mapped you need to run raw SQL to delete the entity in the first place.


EF Code first = NO WAY. Just one from long list of features which is available in EDMX and it is completely missing in code first. Mapped condition from EDMX does this but it is still problematic because it is hardcoded and cannot be changed (= you will never be able to load deleted entities even if you want to unless you use another EDMX). The solution would be implementation of global filters in EF but EF doesn't have anything like that despite the fact that old Linq-to-entities have them at least for relations (DataLoadOptions.AssociateWith).

This is much more painful in relations where you cannot use eager or lazy loading without loading deleted entities to your application as well and do filtering in your application's memory.


In the Model Designer, select your Task entity, and bring up the Mapping Details window. This should show you the database table your entity is mapped to, and all the columns. Just under where it says "Maps to [YourTable]" you should see an option <Add a Condition>. This should let you set a condition like what you're looking for.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号