I have a Web API in .Net 6 with OData 8 where I expose DTOs to query on.
My entity looks like:
public class MyDbEntity
{
[Key]
public int Id { get; set; }
// FK
public int MyOtherDbEntityId { get; set; }
public virtual MyOtherDbEntity? MyOtherDbEntity { get; set; }
}
My DTO looks like
public class MyDto
{
[Key]
public int Id { get; set; }
// FK
public int MyOtherDbEntityId { get; set; }
public virtual MyOtherDto? MyOtherDto { get; set; }
}
I have used Project() to map the Db Entity to the DTO as shown below:
[EnableQuery]
public async Task<IList<MyDto>> Get()
{
return await DbContext.Set<MyDbEntity>()
.ProjectTo<MyDto>(Mapper.ConfigurationProvider)
.ToListAsync();
}
The API works fine when I run it.
But when I write Integration Tests with mocked database (in memory), the ProjectTo() does not return Dtos. The only way to get it to work is to make the Foreign Key nullable as shown below.
My entity with nullable FK :
public class MyDbEntity
{
[Key]
public int Id { get; set; }
// FK nullable
public int? MyOtherDbEntityId { get; set; }
public virtual MyOtherDbEntity? MyOtherDbEntity { get; set; }
}
My DTO with nullable FK:
public class MyDto
{
[Key]
public int Id { get; set; }
// FK nullable
public int? MyOtherDbEntityId { get; set; }
public virtual MyOtherDto? MyOtherDto { get; set; }
}
Is there a better way to deal with this other than making the FK nullable? Or am I missing something here?