It is necessary to make an equivalent. Anyone in the Entity Framework without a navigation property

There are two tables in my database, Readsand Alarms. Between the relation Reads(1) and Alarms(many) there is a relation from one to many. For various reasons, the foreign key constraint in the table has Alarmsbeen removed. I cannot restore this restriction. The object Readin my Entity Framework model, therefore, does not have a navigation property Alarms.

I have a boolean property in my class ReadViewModelcalled HasAlarms. I want this to be set to trueif the table Alarmshas at least one row related to Read. I know that if there was a navigation property Alarms, I could do it something like this:

var reads = from read in context.Reads
            select new ReadViewModel { . . . };

foreach ( ReadViewModel read in reads ) {
    read.HasAlarms = read.Alarms.Any();
}

However, I no longer have the Alarms navigation property. What is the most effective way to do this in my current situation?

Tony

+3
source share
1 answer

You will need something like this:

foreach ( ReadViewModel read in reads ) {
    read.HasAlarms = context.Alarms.Any(a => a.ReadId == read.Id);
}

You can also perform a join to get the state in a single request:

var results = from r in reads
join a in context.Alarms on r.Id equals a.ReadId into ra // perform a left join
from a in ra.DefaultIfEmpty()                            // on Alarms
select new { Read = r, HasAlarm = a != null };

foreach (var res in results)
   res.Read.HasAlarm = res.HasAlarm;
+4
source

All Articles