Mujadid Mughal
Mujadid Mughal

Reputation: 2663

Calling stored procedure from Entity Framework Core

In Entity Framework 6, we had the option to run a stored procedure that returns a specific model object with code like this:

context.Database.SqlQuery<MyModelClass>("SomeStoredProcedure @p0", param1).ToList();

where MyModelClass represents the result set from the stored procedure.

My question is do we have similar kind of option in Entity Framework Core? So far I've been able to find FromSQL but (I could be wrong) this method expects the dbset name, whereas I want to provide plain model class name (because there could be multiple stored procedures with multiple models)

Any suggestion would be greatly appreciated.

Thanks.

Upvotes: 1

Views: 485

Answers (1)

Mujadid Mughal
Mujadid Mughal

Reputation: 2663

So I figured out that for this kind of scenario we'll have to use Keyless entity types feature provided by Entity Framework Core 3.0. Here is how it worked form me.

First of all, in the OnModelCreating event of DbContext, introduce the entity type like this

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder
            .Entity<MyModelClassName>(m=>
            {
                m.HasNoKey();
            });
    }

Now we'll simply call the stored procedure like this

context.Set<MyModelClassName>().FromSqlRaw("MyStoredProcedureName").ToList();

Thanks.

Upvotes: 1

Related Questions