Linq 怎么使用自定义函数?

zlhxx90 2017-07-04 03:38:02
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和使用自定义函数?
...全文
282 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
zlhxx90 2017-07-06
  • 打赏
  • 举报
回复
引用 1 楼 ilikeff8 的回复:
https://stackoverflow.com/questions/12481868/how-to-use-scalar-valued-function-with-linq-to-entity
终于理解了,我是参照MSDN上2017年的文档,里面竟然用的是废弃的参数。。。 帮了我大忙啊,我忙活了两天,才弄出来这个。
ilikeff8 2017-07-04
  • 打赏
  • 举报
回复
https://stackoverflow.com/questions/12481868/how-to-use-scalar-valued-function-with-linq-to-entity

8,497

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 LINQ
社区管理员
  • LINQ
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧