将EF Core与Automapper结合使用时,我们使结果SQL在同一表上为每个属性进行左连接。
这是我们班级的联系方式-
public class Foo {
public Bar bar { get; set; }
public string id { get; set; }
}
public class Bar {
public Bar {
fooCollection = new HashSet<Foo>();
childBarCollection = new HashSet<ChildBar >();
}
public string id { get; set; }
private ICollection<Foo> fooCollection { get; set; }
private ICollection<ChildBar> childBarCollection { get; set; }
}
public class ChildBar {
public virtual Bar { get; set; }
public string id { get; set; }
public string name { get; set; }
}
尝试执行以下调用时,它会导致多个左联接,而我只希望其中一个:
SELECT [c1].[Id], [c1].[Name], [c2].[Id], [c2].[Name],
FROM [dbo].[Foo] AS [i]
INNER JOIN [dbo].[Bar] AS [c] ON [i].[Id] = [c].[Id]
LEFT JOIN [dbo].[ChildBar] AS [c0] ON [c].[Id] = [c0].[Id]
LEFT JOIN [dbo].[ChildBar] AS [c1] ON [c].[Id] = [c1].[Id]
此呼叫如下:
await this.fooRepository.GetQueryable()
.Include(x => x.Bar).ThenInclude(x => x.ChildBar)
.ProjectTo<DTOReturn>(this.mapper.ConfigurationProvider)
.ToListAsync(cancellationToken)
.ConfigureAwait(false);
对象与数据库之间的映射如下:
FooMap:
builder.HasOne(t => t.bar)
.WithMany(t => t.fooCollection)
.HasForeignKey(x => x.Id);
BarMap:
builder.HasMany(t => t.fooCollection)
.WithOne(t => t.var)
.HasForeignKey(t => t.Id);
builder.HasMany(t => t.childBarCollection)
.WithOne(t => t.Bar)
.HasForeignKey(t => t.Id);
ChildBarMap
builder.HasOne(t => t.bar)
.WithMany(t => t.childBarCollection)
.HasForeignKey(d => d.Id);
以下是映射配置文件:
FooMappingProfile
this.CreateMap<Foo, DTOReturn>()
.ForMember(x => x.DTO2, opts => opts.MapFrom(r => r.Bar))
BarMappingProfile
this.CreateMap<Bar, DTO2>()
.ForMember(x => x.Id, opts => opts.MapFrom(r => r.ChildBar.Id))
.ForMember(x => x.Name, opts => opts.MapFrom(r => r.ChildBar.name));
ChildBarMapping :
this.CreateMap<ChildBar, DTO2>()
.ForMember(x => x.Id, opts => opts.MapFrom(r => r.Id))
.ForMember(x => x.Name, opts => opts.MapFrom(r => r.name));
想知道这是否有人遇到过。上面的示例很粗糙,因为我无法提供业务代码,但这可以说明正在发生的事情。