Reputation: 3707
I'm taking over someone's code and came across this Entity Framework query and I've never seen it done this way. Isn't there a database query every time the .FirstOrDefault is called? So in this case there would be 4 database queries meaning 5 open/close connections to the database? Just trying to understand if this is an ineffective way of doing this which it seems like it to me.
var record = from e in ctx.bio_employee.Where(x => x.emp_id == emp_id)
select new
{
ta.ta_system
,ta.bio_consent_flag
,e.bio_consentform_rid
};
if (record.FirstOrDefault() != null)
{
vm.TASystem = record.FirstOrDefault().ta_system;
vm.bio_consent_flag = record.FirstOrDefault().bio_consent_flag == null ? "N" : record.FirstOrDefault().bio_consent_flag.Trim().ToUpper();
vm.employee_bio_consentform_rid = record.FirstOrDefault().bio_consentform_rid;
}
Upvotes: 2
Views: 177
Reputation: 89141
That executes the same query 4 or 5 separate times, although connection pooling will reuse a single connection. Should be
var query = from e in ctx.bio_employee.Where(x => x.emp_id == emp_id)
select new
{
ta.ta_system
,ta.bio_consent_flag
,e.bio_consentform_rid
};
var result = query.FirstOrDefault();
if (result != null)
{
vm.TASystem = result .ta_system;
vm.bio_consent_flag = result .bio_consent_flag == null ? "N" : result .bio_consent_flag.Trim().ToUpper();
vm.employee_bio_consentform_rid = result.bio_consentform_rid;
}
Upvotes: 2