Create a new DbContext or use the injected DbContext when calling a stored procedure in Entity Core?

asp.net c# dbcontext entity-framework-core

Question

What is the proper way to execute a stored procedure (using the ADO method) in Entity Core?

Should I use the injected dbcontext or should I create a new one?

public class ContactController
{
    private readonly MyDbContext _context;


    public ContactController(MyDbContext context)
    {
        _context = context;
    }


    public IActionResult Search(ContactSearchModel csm, int page)
    {
        //execute using the injected _context?
        using (var command = _context.Database.GetDbConnection().CreateCommand())
        {
            //...
        }

        //or create a new context?
        using (var newContext = new MyDbContext())
        {
            using (var command = newContext.Database.GetDbConnection().CreateCommand())
            {
                //...
            }
         }

    }
}
1
2
2/1/2017 3:13:30 PM

Popular Answer

There shouldn't be any reason to not use the injected one.

If you are asking just because you are only reading the data and want it to be quick, and you're worried about tracking or something, you should just call .AsNoTracking() when calling the DB for your stored proc.

An example:

var users = _context.Users
    .FromSql("EXECUTE dbo.MyUserStoredProc")
    .AsNoTracking()
    .ToList();

See these EF Core docs on Raw SQL and No Tracking.

2
2/1/2017 3:17:37 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow