gpt4 book ai didi

c# - 数据库函数 "cannot be translated into a LINQ to Entities store expression"

转载 作者:行者123 更新时间:2023-12-03 21:29:14 25 4
gpt4 key购买 nike

我正在尝试使用 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 存储表达式

有人可以帮我解决这个问题吗?

谢谢,

最佳答案

这是使它对我有用的修改。
在 OnModelCreating() 方法中,添加以下行:

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
// ...
modelBuilder.Conventions.Add(new FunctionsConvention("dbo", this.GetType()));
}
定义 DbFunction stub 时,请使用以下属性:
    [DbFunction("CodeFirstDatabaseSchema", "Echo")]
public static string Echo(string text)
{
throw new NotSupportedException("Direct calls are not supported.");
}
我从
this link
这是我执行的测试,看看它是否是您遇到的问题: 如果我注释掉上面的 modelBuilder.Conventions.Add 行,我会收到与您收到的类似的错误。

System.NotSupportedException: 'The specified method 'System.String Echo(System.String)' on the type 'try1.ExContext' cannot be translated into a LINQ to Entities store expression.'

关于c# - 数据库函数 "cannot be translated into a LINQ to Entities store expression",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45451383/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com