Hi I have two tables like this:
public class TableA
{
public int IdTableA { get; set; }
public string OtherInfo { get; set; }
public int? IdTableB { get; set; }
public TableB TableB { get; set; }
}
public class TableB
{
public TableB()
{
TableAs = new HashSet<TableA>();
}
public int IdTableB { get; set; }
public string Description { get; set; }
public ICollection<TableA> TableAs { get; set; }
}
The foreign key mapping in table TableA to TableB is something like this:
this.HasOptional(t => t.TableB)
.WithMany(t => t.TableAs)
.HasForeignKey(d => d.IdTableB);
Now I'm trying to select some data from TableA:
context
.TableA
.Select(s => new TableA_DTO
{
IdTableA = s.IdTableA,
OtherInfo = s.OtherInfo,
IdTableB = s.IdTableB,
TableB = new TableB_DTO
{
IdTableB = s.TableB.IdTableB,
Description = s.TableB.Description
}
}).ToList();
The problem that when I have a row in TableA with IdTableB = null. I get this exception:
The cast to value type 'Int32' failed because the materialized value is null. Either the result type's generic parameter or the query must use a nullable type.
How I can select this info with entity framework?