Linq 怎么使用自定义函数?
VS2017, EF6 ,MYSQL。
我第一次学习使用EF和LINQ,有个问题,就是怎么使用自定义函数,以及Mysql自带的函数?
1 比如,mysql有Now()函数,取得数据库时间,怎么在LINQ中使用?
2 我在mysql数据库中,写了几个函数,怎么加载到EF中使用?
比如:
1 要取数据库时间的格式化内容。
(1) 我在.edmx的 <edmx:ConceptualModels>中,加入了
<Schema Namespace="testModel" ...
<Function Name="TestF">
<ReturnType Type="Edm.String"/>
<DefiningExpression>
date_format(NOW(),'%Y%m%d')
</DefiningExpression>
</Function>
(2) 我在一个类中写了对应的自定义函数
<System.Data.Objects.DataClasses.EdmFunction("testModel", "TestF")>
Public Shared Function TestF() As String
Throw New NotSupportedException("Direct calls are not 222.")
End Function
(3)然后在LINQ中写入
Using db As New testEntity
Dim rsSql = From city In db.city
Select dd = dbfunction.TestF()
Dim dataSql = rsSql.FirstOrDefault
(4)执行后直接报错,显示
System.NotSupportedException: LINQ to Entities 不识别方法“System.String TestF()”,因此该方法无法转换为存储表达式。
2 我发现数据库中的存储过程,能直接映射到模型中。数据库的函数却不可以。怎样将Mysql的函数映射到模型中?
3 有没有实际的示例代码,包括LINQ和使用自定义函数?