实体框架6.将edmx DbFunctions迁移为首先进行编码

时间:2018-09-28 05:24:03

标签: c# entity-framework-6 ef-code-first edmx dbfunctions

我们正在从面向实体框架6的数据库优先方法过渡到代码优先 我们有模型

public class Parent
{
    public virtual  int Id { get; set; }
    public virtual DateTimeOffset DateFrom { get; set; }
    public virtual DateTimeOffset DateTo { get; set; }
    //navigation property
    public virtual ICollection<Child> Cildren { get; set; }
}

public class Child {
    public int Id { get; set; }
    public DateTimeOffset DateFrom { get; set; }
    public DateTimeOffset DateTo { get; set; }
    //navigation property
    public virtual Parent Parent { get; set; }
}

我们在edmx中有几个这样的函数(但是有点复杂,函数彼此调用)

    <Function Name="IsParentActive" ReturnType="Edm.Boolean">
      <Parameter Name="Parent" Type="MyContext.Parent" />
      <Parameter Name="time" Type="Edm.DateTimeOffset" Nullable="false" />
      <DefiningExpression>
        (Parent.DateFrom &lt;= time) AND (Parent.DateTo &gt; time)
      </DefiningExpression>
    </Function>

   <Function Name="IsChildActive" ReturnType="Edm.Boolean">
      <Parameter Name="Child" Type="MyContext.Child" />
      <Parameter Name="time" Type="Edm.DateTimeOffset" Nullable="false" />
      <DefiningExpression>
        (Child.DateFrom &lt;= time) AND (Child.DateTo &gt; time) AND
           MyContext.IsParentActive(Child.Parent, time)
      </DefiningExpression>
    </Function>

在C#代码中,我们有下一个映射

[DbFunction("MyContext", "IsParentActive")]
public static bool IsActive(this Parent parent, DateTimeOffset time) {
  return time >= parent.DateFrom && time < parent.DateTo
}

[DbFunction("MyContext", "IsChildActive")]
public static bool IsActive(this Child child, DateTimeOffset time) {
  return time >= child.DateFrom && time < child.DateTo
     && child.Parent.IsActive(time);
}

我们可以在任何地方的IQueryable中使用它

var result = context.Parents.Where(p => p.IsActive(time));
var result = context.Parents.Where(p => p.Cildren.Any(c => !c.IsActive(time));
var result = context.Cildren.Where(p => p.Parent.IsActive(time));

现在我找不到替代此方法的好方法。

我尝试将C#函数与表达式一起使用,但不适用于子查询(context.Cildren.Where(p => p.Parent.IsActive(time)))

0 个答案:

没有答案