That code works fine for me:
public static int CheckForDRIID(int personID)
{
var someAssociaction = new { ApplicationID = 1, PersonID = 1, PersonApplicationID = 1 };
var associactions = (new[] { someAssociaction }).ToList();
associactions.Add(new { ApplicationID = 2, PersonID = 2, PersonApplicationID = 2 });
int masterIndex =
(from applicationAssociation in associactions
where applicationAssociation.ApplicationID == 1 && applicationAssociation.PersonID == personID
select applicationAssociation.PersonApplicationID).DefaultIfEmpty(-1).Single();
return masterIndex;
}
I just created a sample set of associactions, because I dont have your datacontext. By the way: you can just declare masterIndex
an int
, because you know the type the expression will return, so you dont need a var
.
So the cause for your problem lies somewhere else: the PersonApplicationID
field is not an int
, therefore the compiler does not know which type it should infer for the generic function DefaultIfEmpty
.
Update:
Just tried the above example with setting the PersonApplicationID
property to:
new Nullable<int>(1)
: Throws "Cannot implicitly convert type 'int?' to 'int'"
1f
: Throws "Cannot implicitly convert type 'float' to 'int'"
""
: Throws "The type arguments for method DefaultIfEmpty<TSource>
cannot be inferred from the usage. Try specifying the type arguments explicitly."
So, I assume you are storing strings in your database's PersonApplicationID
field. If so, either change your database, or parse the string to an int in the Linq query:
public static int CheckForDRIID(int personID)
{
using (var context = ConnectDataContext.Create())
{
int masterIndex =
(from applicationAssociation in context.tblApplicationAssociations
where applicationAssociation.ApplicationID == 1 && applicationAssociation.PersonID == personID
select int.Parse(applicationAssociation.PersonApplicationID)).DefaultIfEmpty(-1).Single();
return masterIndex;
}
}