I have a particular unit test that runs fine on my personal PC, but whenever I get TFS to run the test, it fails with the following exception –
System.InvalidOperationException: The specified cast from a
materialized 'System.Int32' type to a nullable 'Country' type is not
valid.
By following the stack trace, it has a problem with the following method –
public IEnumerable<IAddress> AddressSelectAll(long userID)
{
using (var context = new Entities())
{
var addresses = context.Customers
.Where(x => x.UserId == userID)
.Select(y => new Address
{
Address1 = y.Address1,
Address2 = y.Address2,
Address3 = y.Address3,
AddressID = y.AddressId,
City = y.City,
Country = y.Country != null ? (Country)y.Country : (Country?)null,
Postcode = y.Postcode,
State = y.State,
RecordEntryDate = y.RecordEntryDate,
Type = (AddressType)EFFunctions.ConvertToInt32(y.AddressType),
UserID = y.UserId
}).ToList();
return addresses.ToList();
}
}
In case it's relevant (doubt it is), my EFFunctions class is defined as –
public static class EFFunctions
{
[EdmFunction("Model", "ConvertToInt32")]
public static int ConvertToInt32(string text)
{
var result = string.IsNullOrEmpty(text) ? 0 : Convert.ToInt32(text);
return result;
}
}
And my .edmx has the following in it –
<Function Name="ConvertToInt32" ReturnType="Edm.Int32">
<Parameter Name="v" Type="Edm.String" />
<DefiningExpression>
CAST(v AS Edm.Int32)
</DefiningExpression>
</Function>
Is anyone able to tell me what I'm doing wrong?
Best Answer
Your problem is probably with the line (or part of line)
You cast the value to Country in one case and Country? in another. Perhaps you could replace the value with -1, or, probably more reliably, change the Customer.Country type to Country? instead of Country.