ABP Zero中Many-To-Many关系数据加载的一点心得
在最近的项目开发中,需要用到“多对多”关系的显示与处理。在EF Core中的“多对多”关系通常都是在需要建立关系的两个类中定义ICollection类型的集合属性,这样EF Core就会自动为你创建“多对多”关系表。因为需要在UI中显示两者之前的关系,在ABP框架中需要使用“Repository”对象操作数据库,但Repository并没有提供“Include”方法,无法直接实际数据的加载。在这个过程中需要转变一下思想,可以通过Repository对象的“GetAllIncluding”方法实际关联属性的数据加载。
例:
public async Task<GetServiceForEditOutput> GetServiceForEdit(EntityDto<Guid> input) { var service = await _serviceRepository.FirstOrDefaultAsync(input.Id); var output = new GetServiceForEditOutput { Service = ObjectMapper.Map<CreateOrEditServiceDto>(service) }; output.Taxes = _taxesRepository .GetAllIncluding(p => p.Services) .Select(t => new ComboboxItemDto() { Value = t.Id.ToString(), DisplayText = t.Code, IsSelected = t.Services.Contains(service) }) .ToList(); return output; }
有的时候真的需要自已转换一下思维的方式,就可以拨云见日了。