Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF5 need update ContainerName.FunctionImportName for accessing Stored Procedure when updating models, Any charming solution?

I'm new to entity framework, please forgive me if my question is too simple.

I'm using EF5 build my project at the moment, there is one Function Import "GetStockItem" in my project, which calls a stored procedure and returns data from SP. Every time when I "Update Model from database" from Model Diagram, the update wizard reflects the changes of database without problem, but GetStockItem stops working. The error message when I call GetStockItem is:

"The value of EntityCommand.CommandText is not valid for a StoredProcedure command. The EntityCommand.CommandText value must be of the form 'ContainerName.FunctionImportName'."

The solution, as instructed in the error message is clear, all I need is to add ContainerName. before the FunctionImportName (GetStockItem in my case) in the context.cs file.

My question is how can I avoid the from happening every time when I update models from database? It's quite annoying to do this manual thing now and then, and it's easy to forget to do this then cause users' complaint.

Hope someone can enlighten me with charming solution! Cheers!

like image 924
Yang Li Avatar asked Dec 27 '22 01:12

Yang Li


1 Answers

I just ran into this using EF5/DbContext. The solution I found was to edit the T4 template ([Model].Context.tt) that generates the DbContext.

In this file, locate the instructions for generating the ExecuteFunction call. For me, it started on line 288:

public string ExecuteFunction(EdmFunction edmFunction, string modelNamespace, bool includeMergeOption)
{
    var parameters = _typeMapper.GetParameters(edmFunction);
    var returnType = _typeMapper.GetReturnType(edmFunction);

    var callParams = _code.StringBefore(", ", String.Join(", ", parameters.Select(p => p.ExecuteParameterName).ToArray()));
    if (includeMergeOption)
    {
        callParams = ", mergeOption" + callParams;
    }

    return string.Format(
        CultureInfo.InvariantCulture,
        "return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction{0}(\"{1}\"{2});",
        returnType == null ? "" : "<" + _typeMapper.GetTypeName(returnType, modelNamespace) + ">",
        edmFunction.Name,
        callParams);
}

Modify the return line so that edmFunction.Name is replaced with edmFunction.FullName and upon saving, the Function Import code will be regenerated using fully-qualified names.

like image 104
Technobabble Avatar answered Apr 27 '23 06:04

Technobabble