C# EntityFramework 6.0 - 如何在 EntityTypeConfiguration 中使用 Where 语句?

C# EntityFramework 6.0 - How to use Where Statement in EntityTypeConfiguration?

我有 2 个 类 这样的:

Parent.cs

public class Parent
{
   public int Id {get;set;}
   public virtual ICollection<Child> Children { get; set; }
}

Child.cs

public class Child
{
    public int Id {get;set;}
    public ItemStatusType ItemStatusTyp { get; set; }
    public int ParentId {get;set;}

    [ForeignKey("ParentId")]
    public virtual Parent Parent { get; set; }
}

ItemStatusType.cs

public enum ItemStatusType
    {
        Active = 1,
        Deactive = 2,
        Deleted = 3
    }

我想要的是以某种方式检索 always active 而不是 deleted那些。由于我没有实际删除记录,我只是将 ItemStatusType 更新为 Deleted 状态。

所以,当我说 ParentObj.Children 时,我只想检索活动的那些而不进一步使用 Where 条件。

到目前为止,这是我所做的,但在运行时给出了一个例外,我在后面声明:

public class ParentConfiguration : EntityTypeConfiguration<Parent>
{
     public ParentConfiguration()
     {
             HasMany(c => c.Children.Where(p => p.ItemStatusTyp != ItemStatusType.Deleted).ToList())
                .WithRequired(c => c.Parent)
                .HasForeignKey(c => c.ParentId)
                ;
     }
}

运行时异常:

The expression 'c => c.Children.Where(p => (Convert(p.ItemStatusTyp) != 3)).ToList()' is not a valid property expression. The expression should represent a property: C#: 't => t.MyProperty' VB.Net: 'Function(t) t.MyProperty'.

我必须在表达式后使用ToList,否则编译不通过。

我想做什么才是正确的?

提前致谢,

您不能在流畅的 属性 映射中使用 Where 或任何其他逻辑 - 那只是配置。

基本上你不能用声明的方式解决你需要的东西。

有一些变通方法可用于一级实体,例如实现您自己的扩展 MySet<T>,它将 return .Set<T>.Where(x => x.ItemStatusType != ItemStatusType.Deleted) 并在任何地方使用它,但是这不会解决子集合的过滤问题。

你可以硬着头皮准备一组单独的实体来选择数据,基本上应该基于数据库视图或存储过程;您将必须为每个实体创建单独的视图,因此您将能够结合基于这些视图实体的任何关系中的选择。

为了插入,您需要将实体映射到 "real" 表上。不确定是否值得,但在某些情况下可能会。