简体   繁体   中英

EntityFramework MySQL retrieves results for counting

I am using EntityFramework 6 with the official MySQL provider.

I have a database containing a list of VenuePlans which each consist of Areas. In order to show these values I am using this very simple LINQ query:

model.VenuePlans = CurrentOrganization.VenuePlans.Select(p => new ViewModels.VenuePlans.IndexViewModel.VenuePlan
    {
        ID = p.MaskID,
        Name = p.DisplayName,
        AreaCount = p.VenuePlans_Areas.Count()
    }).ToArray();

But when looking at the executed queries using MiniProfiler I see that this results in duplicate queries as follows:

Retrieving the VenuePlans:

SELECT
`Extent1`.`PlanID`, 
`Extent1`.`MaskID`, 
`Extent1`.`DisplayName`, 
`Extent1`.`OrganizationID`, 
`Extent1`.`SVG`
FROM `VenuePlans` AS `Extent1`
 WHERE `Extent1`.`OrganizationID` = @EntityKeyValue1

Retrieving the Areas for the first VenuePlan:

SELECT
`Extent1`.`AreaID`, 
`Extent1`.`PlanID`, 
`Extent1`.`DisplayName`, 
`Extent1`.`MaskID`, 
`Extent1`.`FillColor`, 
`Extent1`.`InternalName`
FROM `VenuePlans_Areas` AS `Extent1`
 WHERE `Extent1`.`PlanID` = @EntityKeyValue1

Now this latter query is repeated for every area present in the database.

CurrentOrganization is an instance of another model retrieved earlier. Now when writing the query directly on the DbContext instance I don't have this issue:

model.VenuePlans = DbContext.VenuePlans
        .Where(p => p.OrganizationID == CurrentOrganization.OrganizationID)
        .Select(p => new ViewModels.VenuePlans.IndexViewModel.VenuePlan
        {
            ID = p.MaskID,
            Name = p.DisplayName,
            AreaCount = p.VenuePlans_Areas.Count()
        }).ToArray();

What is the reason for this?

DbContext is a variable declared in my BaseController which returns an instance of the current DbContext stored in HttpRequest.Items.

What can I do to prevent this behavior?

I've never found the MySql Linq stuff to be very good. I used it recently, and had to use ToList earlier than I would have liked to stop the query generation from spouting gibberish.

Armed with the knowledge that Linq to MySql is broken, and it's not just you, you'd be best using the version of the query that's fluid from your context instead of from your object.

Having said that, I'd be interesting in seeing if anybody does have a solution, because I tend to avoid Linq when using MySql.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM