【发布时间】:2018-01-09 02:54:21
【问题描述】:
我正在尝试使用 linq to sql 访问数据库功能。这里是我的 SQL 标量函数:
CREATE FUNCTION Echo(@text NVARCHAR(MAX))
RETURNS NVARCHAR(MAX) AS
BEGIN
RETURN @text;
END;
我创建了一个名为 EntityFunction 的类来调用 Sql Server 中的函数:
public static class EntityFunctions
{
[DbFunction("SqlServer", "Echo")]
public static string Echo(string parameter)
{
throw new NotImplementedException();
}
}
这是我的 DbContext:
public class MainDbContext : DbContext
{
#region Properties
/// <summary>
/// List of accounts in database.
/// </summary>
public DbSet<Account> Accounts { get; set; }
#endregion
#region Constructor
/// <summary>
/// Initiate context with default settings.
/// </summary>
public MainDbContext() : base(nameof(MainDbContext))
{
}
#endregion
#region Methods
/// <summary>
/// Called when model is being created.
/// </summary>
/// <param name="modelBuilder"></param>
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingEntitySetNameConvention>();
base.OnModelCreating(modelBuilder);
}
#endregion
}
一切似乎都很好,但是当我使用这段代码时:
private static void Main(string[] args)
{
var context = new MainDbContext();
var accounts = context.Accounts.Select(x => EntityFunctions.Echo(x.Email)).ToList();
}
应用程序抛出异常:类型“MySqlEntityFramework.Models.EntityFunctions”上的指定方法“System.String Echo(System.String)”无法转换为 LINQ to Entities 存储表达式
谁能帮我解决这个问题?
谢谢,
【问题讨论】:
-
搜索错误“无法转换为 LINQ to Entities 存储表达式”并阅读。另外,请只选择 一个 版本。 EF4 还是 EF6?它们是不同的。
-
消息很明显:您不能在 LINQ to Entities SELECT 查询中使用
Echo方法。即使使用了DbFunctionAttribute,Echo方法的返回类型也是错误的 - 要在 LINQ to Entities 中使用自定义扩展方法,该方法必须返回IQueryable<T>。 -
@user2864740,你能给我一个链接吗?我在 Stackoverflow 上搜索过所有帖子,其中大部分是关于存储过程的。
-
也许这会对你有所帮助:stackoverflow.com/a/58136154/10406502
标签: c# linq sql-server-2012 entity-framework-4 entity-framework-6