0

I am doing for testing a small application with ASP.NET Core 6 MVC and Entity Framework Core.

I generated the database for testing based on the model.

Here is my dbContext:

using COBRAAuthentication.Repository.Models;
using Microsoft.EntityFrameworkCore;

namespace COBRAAuthentication.Repository.Data
{
    public class CobraDbContext : DbContext
    {
        public CobraDbContext(DbContextOptions<CobraDbContext> options)
        : base(options)
        {
        }

        public DbSet<AspNetUser> AspNetUsers { get; set; }

        protected override void OnModelCreating(ModelBuilder builder)
        {
            base.OnModelCreating(builder);
        }
    }
}

and my model class:

namespace COBRAAuthentication.Repository.Models
{
    public class AspNetUser : IEntity
    {
        public int Id { get; set; } 
        public string FirstName { get; set; } = String.Empty;
        public string LastName { get; set; } = String.Empty;
        public string UserName { get; set; } = String.Empty;
        public string Email { get; set; } = String.Empty;
        public DateTime AddedDate { get; set; }
        public DateTime ModifiedDate { get; set; }
    }

    public interface IEntity
    {
        public int Id { get; set; }
        public DateTime AddedDate { get; set; }
        public DateTime ModifiedDate { get; set; }
    }
}

After generating the database, I added a stored procedure that is not mapped in the model.

I want to call this stored procedure, but anything I try, I get different errors

namespace COBRAAuthentication.Repository.Repositories
{
    public class GenericRepository<TEntity> : IGenericRepository<TEntity>
     where TEntity : class, IEntity
    {
        private readonly CobraDbContext _dbContext;

        public GenericRepository(CobraDbContext dbContext)
        {
            _dbContext = dbContext;
        }

        public IQueryable<TEntity>GetAllSP()
        {
            string studentName = _dbContext.Database.SqlQuery<TEntity> ("exec SP").ToList();

            // or
            var data = _dbContext.Database.SqlQueryRaw<TEntity>("exec SP" );
    }
}

When I use SqlQuery I get an error

Can not convert from 'string' to 'System.FormattableString'

When I use SqlQueryRaw, the code does not execute at all.

How can I execute a stored procedure that it is not mapped?

Thanks

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Diego
  • 2,238
  • 4
  • 31
  • 68
  • Try EF Core Power Tools – ErikEJ Nov 15 '22 at 20:12
  • Did you consider using [keyless entity types](https://learn.microsoft.com/en-us/ef/core/modeling/keyless-entity-types?tabs=data-annotations) and [FromSql](https://learn.microsoft.com/en-us/ef/core/querying/sql-queries)? Maybe [this answer](https://stackoverflow.com/a/50452479/18789859) can be used as a reference. – Chen Nov 16 '22 at 05:27

0 Answers0