在实体框架中映射/使用内置的MySQL函数



我希望这是一个非常简单的问题:我想像实体框架 6 中的 YEARWEEK 或 INSERT 一样使用内置的 MySQL 函数(类似于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.");
}
}

最新更新