Premise
We have an application in .NET 4.7.2 using Entity Framework 6 db-first (with an `.edmx` file). Until now we have used only Devart for Oracle as Provider for EF, but now we need to handle SQL Server databases. All our ASP.NET MVC 5 views (hundreds) need to work with `System.Data.SqlClient`. No problem, query works well except for...Issue
The issue is related to foreign key and referenced table.The error is the following:
InvalidOperationException: the cast to value type 'System.Int32' failed because the materialized value is null. Either the result type's generic parameter or the query must use a nullable type.
at System.Data.Entity.Core.Common.Internal.Materialization.ErrorHandlingValueReader
1.GetValue(DbDataReader reader, Int32 ordinal) +177 at lambda_method(Closure , Shaper ) +1146 at System.Data.Entity.Core.Common.Internal.Materialization.Coordinator
1.ReadNextElement(Shaper shaper) +384
at System.Data.Entity.Core.Common.Internal.Materialization.SimpleEnumerator.MoveNext() +88
at System.Linq.Buffer1..ctor(IEnumerable
1 source) +284
at System.Linq.Enumerable.ToArray(IEnumerable`1 source) +90
at Medici.MediciService.GetMedici(GetMediciQuery param)
The query example:
var medici = _dbContext.Medici
.Select(x => new MediciDto
{
Id = x.Id,
Nome = x.Nome,
Cognome = x.Cognome,
TipoMedico = new TipoMedico
{
Codice = x.TipoMedico.Id,
Descrizione = x.TipoMedico.Desc,
}
})
.ToArray();
And these are the classes:
public class MediciDto
{
public int Id{ get; set; }
public string Nome { get; set; }
public string Cognome { get; set; }
public TipoMedico TipoMedico { get; set; }
}
public class TipoMedico
{
public int Id{ get; set; }
public string Descrizione { get; set; }
}
The issue is bound to the fact that the foreign key in table Medici
is nullable, but the id on the referenced table not. Devart provider for EF6 handle this setting the default value (in this case zero), while SQL Server provider runs into the InvalidOperationException
.
So, in conclusion our question is: is there a way to configure the same behaviour as Oracle Devart Provider as default for Entity Framework? We can't review all queries to handle a check null value. We don't have all this time.