Dapper-like Multi Query with EF Core

早过忘川 提交于 2021-01-29 05:11:26

问题


With dapper it is pretty easy to run mulitple queries in one run:

string sql = "SELECT * FROM Invoice WHERE InvoiceID = @InvoiceID; SELECT * FROM InvoiceItem WHERE InvoiceID = @InvoiceID;";

using (var connection = My.ConnectionFactory())
{
    connection.Open();

    using (var multi = connection.QueryMultiple(sql, new {InvoiceID = 1}))
    {
        var invoice = multi.Read<Invoice>().First();
        var invoiceItems = multi.Read<InvoiceItem>().ToList();
    }
}

How to archieve this with EFCore?

I found solutions like

var query = from _ in db.Invoices
            select new {
                Invoice = db.Invoices.Single(x=>x.InvoiceId == 1),
                InvoiceItems = db.InvoiceItems.Where(x=>x.InvoiceId == 1),
            }

but this does not work. I can see in the profiling this runs two queries in two connections. I can even see that the connection is not reused (why?).

How to run multiple queries with EFCore is this a big performance-lack of EFCore? Thanks.


回答1:


Disclaimer: I'm the owner of the project Entity Framework Plus

You are currently looking for the Query Future feature: https://entityframework-plus.net/ef-core-query-future

This feature is often called Future since all query will be materialized when the first immediate action will be executed such as ToList

using Z.EntityFramework.Plus; // Don't forget to include this.
var ctx = new EntitiesContext();

// CREATE a pending list of future queries
var futureCountries = ctx.Countries.Where(x => x.IsActive).Future();
var futureStates = ctx.States.Where(x => x.IsActive).Future();

// TRIGGER all pending queries in one database round trip
// SELECT * FROM Country WHERE IsActive = true;
// SELECT * FROM State WHERE IsActive = true
var countries = futureCountries.ToList();

// futureStates is already resolved and contains the result
var states = futureStates.ToList();

Online Example: https://dotnetfiddle.net/8gwESn

EDIT: Answer Comment

But async is not supported

Sure async is supported, any immediate method is supported such as ToListAsync().

However, make sure the first immediate method as been fully executed (using await for example).




回答2:


The problem was: MultiActiveResults was false.



来源:https://stackoverflow.com/questions/63956996/dapper-like-multi-query-with-ef-core

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!