Home > OS >  C# Entity Framework Core : how to execute stored procedure and get a list of custom data?
C# Entity Framework Core : how to execute stored procedure and get a list of custom data?

Time:05-08

I am trying to call a stored procedure in C# with EF Core. Just returning custom result set which is not linked to any entity.

But I am getting an error:

Cannot create a DbSet for 'ExCoResponse' because this type is not included in the model for the context.

Here is my method:

public async Task<IEnumerable<ExCoResponse>> UpdateAndGetExcoUsers()
{
    return await _context
                     .Query<ExCoResponse>()
                     .FromSql("[dbo].[UsersUpdateExcoDetail]")
                     .ToListAsync();
}

CodePudding user response:

Since i am using Core 2.1 Following worked for me:

public DbQuery<ExcoUser> ExcoUsers { get; set; }

        var result = await _context
            .ExcoUsers.FromSql<ExcoUser>("EXEC [dbo].[UsersUpdateExcoDetail]")
            .ToListAsync();

CodePudding user response:

dot net core 3.0

1- Install Microsoft.EntityFrameworkCore.Relational package

2 - Add Entity and configuration to DbContext Model

public class ApplicationDBContext : DbContext
{
    public DbSet<ExCoResponse> ExCoResponses { get; set; }
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.Entity<ExCoResponse>().HasNoKey();
    } // end OnModelCreating
} // end ApplicationDBContext


     

3- use this query. be careful have used Microsoft.EntityFrameworkCore;

    var result = dBContext
            .Set<ExCoResponse>()
            .FromSqlRaw("exec [dbo].[UsersUpdateExcoDetail]").ToList();
  • Related