DbFunction "cannot be translated into a LINQ to Entities store expression"

Viewed 1387

I'm trying to access database funciton using linq to sql. Herer is my SQL Scalar Function:

CREATE  FUNCTION    Echo(@text NVARCHAR(MAX))
RETURNS NVARCHAR(MAX)       AS
BEGIN
   RETURN @text;
END;

I created a class called EntityFunction to call Functions in Sql Server:

    public static class EntityFunctions
    {
        [DbFunction("SqlServer", "Echo")]
        public static string Echo(string parameter)
        {
            throw new NotImplementedException();
        }
    }

And here is my 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
    }

Everything seems to be fine, but when I used this code:

        private static void Main(string[] args)
        {
            var context = new MainDbContext();
            var accounts = context.Accounts.Select(x => EntityFunctions.Echo(x.Email)).ToList();

        }

Application threw me an exception : The specified method 'System.String Echo(System.String)' on the type 'MySqlEntityFramework.Models.EntityFunctions' cannot be translated into a LINQ to Entities store expression

Could anyone help me to solve this problem please ?

Thank you,

1 Answers

Here's are the modifications that got it working for me.

In the OnModelCreating() method, add this line:

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        // ...
        modelBuilder.Conventions.Add(new FunctionsConvention("dbo", this.GetType()));
    }

When defining the DbFunction stub use these attributes:

    [DbFunction("CodeFirstDatabaseSchema", "Echo")]
    public static string Echo(string text)
    {
        throw new NotSupportedException("Direct calls are not supported.");
    }

I took ideas from this link

Here's the test I performed to see if it was the issue you were having: If I comment out the modelBuilder.Conventions.Add line above, I receive a similar error to what you were receiving.

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.'

Related