Map/使用实体框架中的内置mysql函数

3z6pesqy  于 2021-06-18  发布在  Mysql
关注(0)|答案(1)|浏览(379)

我希望这是一个非常简单的问题:我希望使用内置的mysql函数,就像yearweek或insert in entity framework6(类似于 System.Data.Entity.DbFunctions 命名空间)。有没有办法向这些函数添加Map?
我已经尝试过通过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>

在我的代码里:

[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();

知道这里怎么了吗?

41zrol4v

41zrol4v1#

我终于解决了这个问题,解决方法非常简单:给 edmx:ConceptualModels 是不必要的。你只要加上 edmx:StorageModels 定义并正确调用。下面是我修改的代码,其中包含mysql内置函数insert和yearweek的示例性实现:

<!-- 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.");
    }
}

相关问题