简体   繁体   中英

How do I contruct a query to find unmatched entities in related table with Entity Framework and .NET 5.0?

I am using .NET (Core?) 5.0 and Entity Framework with a MySQL 8.0 database using the Pomelo driver. In a previous version of .NET Core 3.1 and MySQL 5.7 I was able to create a query or lambda expression to find all records in one table that DO NOT have a corresponding record in another related table for a given user. Here is the method as it worked before:

public int GetUnacknowledgedAlarmEventsCount(string name, ApplicationUser user)
{
    int count = 0;
    if (name != null && user != null)
    {
        count = (from ae in AlarmEvents
                 where ae.Alarm.Name.StartsWith(name) && !ae.Acks.Any(a => a.UserId == user.Id)
                 select ae).Count();
    }
    return count;
}

The structure of the tables behind this query are simplified as:

Alarms
------
Id
Name

AlarmEvents
-----------
Id
AlarmId

AlarmEventAcks
--------------
Id
AlarmEventId
UserId

Users
-----
Id

I hope the relationships are obvious based on the names. Anyway, I am trying to determine which alarms events have NOT been acknowledged by a given user. I know I can do this in multiple steps with a huge performance hit, but I am hoping to put all the work on the database query just like it worked in a previous version. Not sure why it does not work the same as before other than the lazy loading not kicking in like previous versions did by default.

I tried changing this query to use Lambda expressions with Includes like below, but that didn't work either:

public int GetUnacknowledgedAlarmEventsCount(string station, ApplicationUser user)
{
    int count = 0;
    if (station != null && user != null)
    {
        count = AlarmEvents.Include(a => a.Alarm).Include(a => a.Acks).Where(a => a.Alarm.Name.StartsWith(station)).Where(a => !a.Acks.Any(a => a.UserId == user.Id)).Count();
    }
    return count;
}

So, I am stuck trying to figure out the best way to construct this query to work with the changes to Entity Framework for the newest version of .NET. Anyone have any suggestions or help? Thanks.

After updating everything to make sure everything was in sync with current versions of drivers, it is now working again using the original queries. I hate upgrading stable, working code to use newer versions of the technologies and APIs.

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