Reputation:
I have something like this:
public Assignments GetAssignmentsForProider(string provider_k, string recordType)
{
if (recordType == "A")
{
var query = from ea in this.Context.Assignments
where ea.Provider_K == provider_k
&& ea.Active == true
&& ea.RecordType == "A"
select ea;
return query.FirstOrDefault();
}
else if (recordType == "E")
{
var query = from ea in this.Context.Assignments
where ea.Provider_K == provider_k
&& ea.RecordType == "E"
select ea;
return query.FirstOrDefault();
}
}
Two problems:
It doesn't compile! because it needs a default return statement too and I am not sure what to return really but in my program it will never happen that none of those if conditions happen. I am always in the first one or second one.
Really all they are different in is in first one we check for Active == true
and in second one we don't. So is there a better way of writing this too?
Upvotes: 1
Views: 329
Reputation: 6415
One way to chain your conditions ...
public Assignments GetAssignmentsForProider(string provider_k, string recordType)
{
var query = from ea in this.Context.Assignments
where ea.Provider_K == provider_k
select ea;
if (recordType == "A")
{
query = from q in query
where q.Active == true
&& q.RecordType == "A"
select q;
}
else if (recordType == "E")
{
query = from q in query
where q.RecordType == "E"
select q;
}
return query;
}
But Bjarke Søgaard has the better method for filtering on record type, because your criteria parameter directly matches on the query data ... so you could just use it directly.
Upvotes: 1
Reputation: 46909
I would probably write it like this:
public Assignments GetAssignmentsForProider(string provider_k, string recordType)
{
var query = from ea in this.Context.Assignments
where ea.Provider_K == provider_k &&
ea.RecordType == recordType
select ea;
if (recordType == "A")
return query.Where(ea => ea.Active).FirstOrDefault();
else if (recordType == "E")
return query.FirstOrDefault();
return null;
}
Upvotes: 1
Reputation: 1310
Something like this?
public Assignments GetAssignmentsForProider(string provider_k, string recordType)
{
var query = from ea in this.Context.Assignments
where ea.Provider_K == provider_k
&& ea.RecordType == recordType
&& (recordType == "E" ? true : ea.Active)
select ea;
return query.FirstOrDefault();
}
This should satisfy your need.
Upvotes: 2