I want to generate a query that uses an inner join for a one to one relationship using a navigation property. This is for an existing database that I cannot change.
Here are what my entities look like:
[Table("Info")]
public class Info
{
[Key]
public int InfoId { get; set; }
public string Name { get; set; }
public virtual MoreInfo MoreInfo { get; set; }
}
[Table("MoreInfo")]
public class MoreInfo
{
[Key]
public int InfoId { get; set; }
public string OtherName { get; set; }
public int OtherNumber { get; set; }
}
and here is my query:
var x = await context.Infos
.Select(info => new
{
info.InfoId,
info.Name,
info.MoreInfo.OtherName,
info.MoreInfo.OtherNumber
})
.ToListAsync();
this produces this SQL (which uses a left join):
SELECT [info].[InfoId], [info].[Name], [info.MoreInfo].[OtherName], [info.MoreInfo].[OtherNumber]
FROM [Info] AS [info]
LEFT JOIN [MoreInfo] AS [info.MoreInfo] ON [info].[InfoId] = [info.MoreInfo].[InfoId]
This will cause an error if there are records in Info that are not in MoreInfo, which is why I want to do an inner join.
I have tried various option in OnModelCreating such as
modelBuilder.Entity<Info>()
.HasOne(p => p.MoreInfo)
.WithOne()
.IsRequired();
or setting the navigation property as Required
[Table("Info")]
public class Info
{
[Key]
public int InfoId { get; set; }
public string Name { get; set; }
[Required]
public virtual MoreInfo MoreInfo { get; set; }
}
or using an include in the query
var x = await context.Infos
.Include(info => info.MoreInfo)
.Select(info => new
{
info.InfoId,
info.Name,
info.MoreInfo.OtherName,
info.MoreInfo.OtherNumber
})
.ToListAsync();
but none of those changed the join.
I am able to get an inner join by using the join function, and not using the navigation property, but I would like to avoid this if possible. The syntax is ugly and requires me to add MoreInfos to the context. If it is possible, I would like to create an inner join using a navigation property.
var x = await context.Infos
.Join(context.MoreInfos, info => info.InfoId, moreInfo => moreInfo.InfoId, (info, moreInfo) =>
new
{
info.InfoId,
info.Name,
moreInfo.OtherName,
moreInfo.OtherNumber
})
.ToListAsync();
produces the correct SQL
SELECT [info].[InfoId], [info].[Name], [moreInfo].[OtherName], [moreInfo].[OtherNumber]
FROM [Info] AS [info]
INNER JOIN [MoreInfo] AS [moreInfo] ON [info].[InfoId] = [moreInfo].[InfoId]
but I'd rather uses the navigation property.