Stored Procedure in dot net core

c# entity-framework-core stored-procedures

Question

Below is my method, which calls a stored procedure.

public List<int> GetActivityListforUser(string userId)
{
    IList<int> results = new List<int>();            
    context.LoadStoredProc("dbo.GetRegionOrganizationActivities")
            .WithSqlParam("userId", userId)
            .ExecuteStoredProc((handler) =>
            {    
                results = handler.ReadToList<int>().ToList();
            });

    return results.ToList();
}

My stored procedure dbo.GetRegionOrganizationActivities, returns only one column Id, which is the required result up on passing the parameter userId.

My issue is in the following line:

return results.ToList();

I can see all the list that comes from the stored procedure, but all int values are 0. The list count matches with stored proc result count, but values should be example: 1,2,3, etc. it shows 0,0,0, etc.

Can any one provide some insight on what I am doing wrong?

1
0
7/25/2018 10:05:32 PM

Accepted Answer

It seems you are using the Snickler.EFCore nuget package with EF Core.

Short answer: You'll have to create a complex object to allow this library to map your result set, something like:

public class RegionOrganizationActivity
{
    public int Id { get; set; }
}

then you can use this to extract your list of integers:

public List<int> GetActivityListforUser(string userId)
{
    IList<RegionOrganizationActivity> results = new List<RegionOrganizationActivity>();            
    context.LoadStoredProc("dbo.GetRegionOrganizationActivities")
            .WithSqlParam("userId", userId)
            .ExecuteStoredProc((handler) =>
            {    
                results = handler.ReadToList<RegionOrganizationActivity>();
            });

        return results.Select(activity => activity.Id).ToList();
    }

Explanation:

handler.ReadToList<int>() won't work here because the ReadToList<T> implementation only supports complex types. It is assuming it needs to create an instance of T and try to match properties to the columns.

Because there are no properties to match when T is int, the latter part fails. This explains why you are getting all values of 0: the only thing the method manages to do is an Activator.CreateInstance<int>() which will return 0.

Their other helper method ReadToValue only supports a single result value, which won't work either.

This means you can't use this library to map your result straight to a List<int>. So you'll need to use complex object to match the result set.

0
7/25/2018 7:50:34 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow