Search code examples
sql-serverentity-frameworkstored-proceduresfacebook-c#-sdklegacy

EF 6 - Stored Procedure Duplicate Result Column


I'm in the process of migrating from a legacy system. The database cannot be modified - including adding/modifying stored procedures.

I've added a stored procedure to an EDMX model successfully, it generated the following code:

public virtual ObjectResult<sp_GetUserInfoByUID_Result> sp_GetUserInfoByUID(Nullable<System.Guid> sessionID, Nullable<System.Guid> userUID)
{
    var sessionIDParameter = sessionID.HasValue ?
            new ObjectParameter("SessionID", sessionID) :
            new ObjectParameter("SessionID", typeof(System.Guid));

    var userUIDParameter = userUID.HasValue ?
            new ObjectParameter("userUID", userUID) :
            new ObjectParameter("userUID", typeof(System.Guid));

    return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction<sp_GetUserInfoByUID_Result>("sp_GetUserInfoByUID", sessionIDParameter, userUIDParameter);
}

However, I get the following runtime error:

The data reader is incompatible with the specified 'MyApp.Repository.sp_GetUserInfoByUID_Result'. A member of the type, 'useraccount_uid1', does not have a corresponding column in the data reader with the same name.

So it looks like EF generated two mappings: useraccount_uid and useraccount_uid1. This is because the stored procedure returns a table with two columns named useraccount_uid.

Is there a way to get round this in the EF model?


Solution

  • Turns out the solution was really simple, I'd just overlooked how EF modeled stored procedures. When you add a stored procedure to the Model, by default it actually adds a couple of references.

    1. A mapping from the model to the basic function in the DB - you cannot edit these mappings.
    2. A "Function Import" - this is the part which maps result sets to code models.

    So all I had to was look for the Function Imports folder in the EDMX Model Browser. In here the stored procedure was listed. If you right-click on the function you'll see the "Function Import Mapping" option. This will open the Mappings Detail window. Here I could simply correct the column naming.