简体   繁体   中英

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

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();
}

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();

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM