Base solution for your next web application
Open Closed

How to do a simple sql query within the dbContext ? #4899


User avatar
0
squaresunion created

Hello, How to do a simple sql query withing the dbContext. I mean everything we usually used do not work: dbContext.Database.SqlQuery is not available. Why is this not available? How do to it?

Regards


5 Answer(s)
  • User Avatar
    0
    ismcagdas created
    Support Team

    @SquaresUnion,

    Are you using EF 6.x or EF Core ? Can you share the query you have tried and the error message ?

  • User Avatar
    0
    squaresunion created

    Hello I am using EF Core. I need to inject the dbcontext in my service to perform custom sql queries. basically to query sequence. Do u know how to do it?

  • User Avatar
    0
    bbakermmc created

    Whats the query you are trying to run?

  • User Avatar
    0
    squaresunion created

    I found it for others you need to inject

    IDbContextProvider<AbpDbContext> _dbContext;

    then u canhave the dbcontext doing

    _dbContext.GetDbContext()

    Yeeehh!!!

  • User Avatar
    0
    alper created
    Support Team

    You can also create a custom repository for the entity. In custom repositories there's a shortcut method GetDbContext() to retrieve your DbContext.

    public class SubscriptionPaymentRepository : AbpZeroTemplateRepositoryBase<SubscriptionPayment, long>, ISubscriptionPaymentRepository
        {
            public SubscriptionPaymentRepository(IDbContextProvider<AbpZeroTemplateDbContext> dbContextProvider)
                : base(dbContextProvider)
            {
            }
    
            public async Task UpdateMyDbWithSqlCommand()
            {
                await GetDbContext().Database.ExecuteSqlCommandAsync("Update myTable set MyField=1 where MyFilter=2");
            }
        }