我希望这是一个简单的问题:我想像Entity Framework 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();
有什么想法吗?
答案 0 :(得分:1)
我终于解决了问题,解决方案非常简单:不需要向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.");
}
}