开发者

Soft deletes, navigation properties in EF4 CTP5 POCO

Basically, I want to use soft deletes, but have the navgiation properties not show the soft deleted records. Are there any ways to intercept the navigation property queries on POCO objects in entity framework?

Very simple example:

 public class Product
 {
    public int Id { get; set;}
    public string Name { get; set;}
    public int? CategoryId { get; set;}
    public virtual Category Category { get; set;}
    public bool IsDeleted { get; set;}
 }    

public class Category
{
    public int Id{ get; set; }
    public string Name { get; set; }
    public virtual ICollection<Product> Products { get; set;}
}

I can easily insert the criteria into my repository so that it doesn't return any products where IsDeleted==true.

However, I can't see how to accomplish this for other objects th开发者_如何学运维at have 'soft deleted' entites in their navigation properties.

IE If I access myCategory.Products (where myCategory is a Category) it should not show any products where IsDeleted==true

I could potentially workaround this using an additional property of Category

public ICollection<Product> CurrentProducts
{
    get
    {
         return this.Products.Where(p=>!p.IsDeleted);
    }
}

But that isn't the elegant solution I'm looking for. Is there a way to 'attach' criteria to the navigation property or any better solutions for how to handle this?


Maybe You should look at this from another perspective. Might help. Certainly won't hurt. :)


public class CategoryWithNoDeletedItems : Category
{
    private ICollection<Product> _products;
    public override ICollection<Product> Products
    {
        get
        {
            return _products;
        }
        set
        {
            if (value.Any(x => x.IsDeleted))
            {
                _products = value.Where(x => !x.IsDeleted).ToArray();
            }
            else
            {
                _products = value;
            }
        }
    }
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜