InvalidCastException when using a sub query
When using a sub-query I'm getting an InvalidCastException.
It only occurs when the sub queries predicate involves types other than the Id being selected.
For example, the BrokenQueryAsync method below query will work if the predicate.BirthDate and predicate.LastName clauses are removed.
The exception seems to occur before any SQL query is executed. When profiling my SQL database, no query was executed.
Exception message:
System.FormatException: Failed to convert parameter value from a String to a Int32.
Stack trace:
at System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal)
at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info)
at System.String.System.IConvertible.ToInt32(IFormatProvider provider)
at System.Convert.ChangeType(Object value, Type conversionType, IFormatProvider provider)
at System.Data.SqlClient.SqlParameter.CoerceValue(Object value, MetaType destinationType, Boolean& coercedToDataFeed, Boolean& typeChanged, Boolean allowStreaming)
--- End of inner exception stack trace ---
at System.Data.SqlClient.SqlCommand.<>c.<ExecuteDbDataReaderAsync>b__174_0(Task`1 result)
at System.Threading.Tasks.ContinuationResultTaskFromResultTask`2.InnerInvoke()
at System.Threading.Tasks.Task.Execute()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.<ExecuteAsync>d__26.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.EntityFrameworkCore.Query.Internal.AsyncQueryingEnumerable.AsyncEnumerator.<BufferlessMoveNext>d__9.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.EntityFrameworkCore.Storage.Internal.SqlServerExecutionStrategy.<ExecuteAsync>d__6`2.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.EntityFrameworkCore.Query.Internal.AsyncQueryingEnumerable.AsyncEnumerator.<MoveNext>d__8.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Linq.AsyncEnumerable.SelectEnumerableAsyncIterator`2.<MoveNextCore>d__7.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Linq.AsyncEnumerable.AsyncIterator`1.<MoveNext>d__10.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.EntityFrameworkCore.Query.Internal.AsyncLinqOperatorProvider.ExceptionInterceptor`1.EnumeratorExceptionInterceptor.<MoveNext>d__5.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Collections.Generic.AsyncEnumerableHelpers.<ToArrayWithLength>d__1`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Collections.Generic.AsyncEnumerableHelpers.<ToArray>d__0`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at REDACTED.<BrokenQueryAsync>d__49.MoveNext() REDACTED
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
at REDACTED.<ExecuteBrokenQueryAsync>d__39.MoveNext() REDACTED
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.ThreadOperations.ExecuteWithAbortSafety(Action action)
Steps to reproduce
I have created this method to help me diagnose the error.
public async Task BrokenQueryAsync(PredicateModel predicate)
{
using (var database = new DatabaseContext(_settings))
{
var subQuery = from p in database.Policies
from pp in p.PolicyPeople
where (predicate.PolicyTypeId == null || p.PolicyTypeId == predicate.PolicyTypeId)
&& (predicate.BirthDate == null || pp.BirthDate == predicate.BirthDate)
&& (predicate.LastName == null || pp.LastName.Contains(predicate.LastName))
select p.Id;
var query = from p in database.Policies
where subQuery.Contains(p.Id)
select new
{
// Field mappings...
};
// System.InvalidCastException: Failed to convert parameter value from a DateTime to a Int32.
var results = await query.ToArrayAsync();
}
}
public class PredicateModel
{
public int? PolicyTypeId { get; set; }
public DateTime? BirthDate { get; set; }
public string LastName { get; set; }
}
Further technical details
EF Core version: 2.0.0-preview1-final (I updated to 2.0.1 and the issue still occurred) Database Provider: Microsoft.EntityFrameworkCore.SqlServer Operating system: Windows 10 IDE: Visual Studio 2017 15.5.5
This seems to be fixed in current bits. Tried the following repro and got expected results without exception.
class Program
{
static void Main(string[] args)
{
using (var ctx = new MyContext())
{
ctx.Database.EnsureDeleted();
ctx.Database.EnsureCreated();
}
using (var ctx = new MyContext())
{
var person11 = new PolicyPerson { LastName = "Foo", BirthDate = new DateTime(1, 1, 1), PolicyId = 1 };
var person12 = new PolicyPerson { LastName = "Bar", BirthDate = new DateTime(1, 1, 1), PolicyId = 1 };
var pol1 = new Policy { PolicyTypeId = 1, PolicyPeople = new List<PolicyPerson> { person11, person12 } };
var pol2 = new Policy { PolicyTypeId = 2, PolicyPeople = new List<PolicyPerson>() };
ctx.Policies.AddRange(pol1, pol2);
ctx.PolicyPeople.AddRange(person11, person12);
ctx.SaveChanges();
}
var test = new Test();
var task = test.BrokenQueryAsync(new PredicateModel { BirthDate = new DateTime(1, 1, 1), LastName = "Foo", PolicyTypeId = 1 });
task.Wait();
}
}
public class MyContext : DbContext
{
public DbSet<Policy> Policies { get; set; }
public DbSet<PolicyPerson> PolicyPeople { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(@"Server=.;Database=10871;Trusted_Connection=True;MultipleActiveResultSets=True");
}
}
public class Test
{
public async Task BrokenQueryAsync(PredicateModel predicate)
{
using (var database = new MyContext())
{
var subQuery = from p in database.Policies
from pp in p.PolicyPeople
where (predicate.PolicyTypeId == null || p.PolicyTypeId == predicate.PolicyTypeId)
&& (predicate.BirthDate == null || pp.BirthDate == predicate.BirthDate)
&& (predicate.LastName == null || pp.LastName.Contains(predicate.LastName))
select p.Id;
var query = from p in database.Policies
where subQuery.Contains(p.Id)
select new
{
p.Id,
p.PolicyTypeId
};
var results = await query.ToArrayAsync();
}
}
}
public class Policy
{
public int Id { get; set; }
public int PolicyTypeId { get; set; }
public List<PolicyPerson> PolicyPeople { get; set; }
}
public class PolicyPerson
{
public int Id { get; set; }
public int PolicyId { get; set; }
public DateTime BirthDate { get; set; }
public string LastName { get; set; }
}
public class PredicateModel
{
public int? PolicyTypeId { get; set; }
public DateTime? BirthDate { get; set; }
public string LastName { get; set; }
}