在实体框架中的Where条件中调用标量用户定义函数

时间:2014-01-06 06:50:24

标签: c# asp.net sql-server entity-framework user-defined-functions

我有一个SQL函数'DecryptField'

ALTER FUNCTION [dbo].[DecryptField]
(
    @EField as varchar(10)
)
RETURNS varchar(10)
BEGIN

Declare @decrypted varchar(10)  
SET @decrypted = 'Something' + @EField

return @decrypted

END

我想在Entity Framework中调用该函数。(EF版本:6.0目标框架:4.0)。 通过互联网搜索,我找到了一个创建类的解决方案:

public static class UDFFunctions
{
    [EdmFunction("MyModel.Store", "DecryptField")]
    public static string DecryptField(string field)
    {
       // This code will never been run against real SQL database
       // This will help any test requires this method pass
       throw new NotSupportedException("Direct calls not supported");  
    }
}

然后使用此功能:

User user = null;
var query = from u in _context.Users.AsNoTracking()
            where u.Login == userName && UDFFunctions.DecryptField(u.Password) == password
            select u;
user = query.SingleOrDefault();
return user;

我在运行时遇到错误:LINQ to Entities does not recognize the method 'System.String DecryptField(System.String)' method, and this method cannot be translated into a store expression.

如果我遗失任何东西或做错什么,请告诉我。

0 个答案:

没有答案