Map/use Entity Framework 中的内置 MySQL 函数

Map/use built-in MySQL function in Entity Framework

很简单的问题,我希望:我想使用内置的 MySQL 函数,就像 Entity Framework 6 中的 YEARWEEK 或 INSERT(类似于 System.Data.Entity.DbFunctions 命名空间)。有没有办法为这些函数添加映射?

我已经尝试通过 edmx 文件添加它们,但效果不佳。

<!-- edmx:ConceptualModels -->
<Function Name="YearWeek" ReturnType="String">
    <Parameter Name="date" Type="DateTime" />
    <DefiningExpression>
        YEARWEEK(date, 3)
    </DefiningExpression>
</Function>

<!-- edmx:StorageModels -->
<Function Name="YEARWEEK" IsComposable="true" ReturnType="varchar" BuiltIn="true" Aggregate="false" NiladicFunction="false" ParameterTypeSemantics="AllowImplicitConversion">
    <Parameter Name="date" Type="datetime" Mode="In" />
    <Parameter Name="mode" Type="int" Mode="In" />
</Function>

在我的 C# 代码中:

[System.Data.Entity.DbFunction("otrsModel", "YearWeek")]
public static string YearWeek(DateTime date) {
    throw new NotSupportedException("Direct calls are not supported.");
}

现在,这让我感到震惊 System.Data.Entity.Core.EntityCommandCompilationException。内部异常是:"'YEARWEEK' 无法解析为有效类型或函数。"

但是,在同一数据库上调用以下代码工作正常:

var week = db.Database.SqlQuery<dynamic>("SELECT INSERT(YEARWEEK(create_time, 3), 5, 0, '/'), ticket.* AS a FROM ticket").ToList();

知道这里出了什么问题吗?

我终于解决了这个问题,解决方法也很简单:在edmx:ConceptualModels中添加一个定义是不必要的。您只需添加 edmx:StorageModels 定义并正确调用它。这是我修改后的代码,其中包含 MySQL 的内置函数 INSERTYEARWEEK:

的示例性实现
<!-- edmx:StorageModels -->
<Function Name="YEARWEEK" IsComposable="true" ReturnType="varchar" BuiltIn="true" Aggregate="false" NiladicFunction="false" ParameterTypeSemantics="AllowImplicitConversion">
  <Parameter Name="date" Type="datetime" Mode="In" />
  <Parameter Name="mode" Type="int" Mode="In" />
</Function>
<Function Name="INSERT" IsComposable="true" ReturnType="varchar" BuiltIn="true" Aggregate="false" NiladicFunction="false" ParameterTypeSemantics="AllowImplicitConversion">
  <Parameter Name="str" Type="varchar" Mode="In" />
  <Parameter Name="position" Type="int" Mode="In" />
  <Parameter Name="number" Type="int" Mode="In" />
  <Parameter Name="substr" Type="varchar" Mode="In" />
</Function>

以及对应的c#代码:

namespace MySQL_3 {
    class Program {
        static void Main(string[] args) {
            var db = new myEntities();

            var test = db.ticket.Select(t => t.change_time.YearWeek(3).Insert(5, 0, "/"));

            var test2 = test.ToList();

            Console.Read();
        }
    }

    public static class BuiltInFunctions {

        [DbFunction("myModel.Store", "YEARWEEK")]
        public static string YearWeek(this DateTime date, Int32 mode) => throw new NotSupportedException("Direct calls are not supported.");

        [DbFunction("myModel.Store", "INSERT")]
        public static string Insert(this string str, int position, int number, string substr) => throw new NotSupportedException("Direct calls are not supported.");
    }
}