简体   繁体   English

Entity Framework Core,只返回与 Automapper 相关的 id?

[英]Entity Framework Core, return just related id with Automapper?

I am developing a REST Api using .netCore 3.1, EF Core and Automapper.我正在使用 .netCore 3.1、EF Core 和 Automapper 开发 REST Api。

I have the following Entities:我有以下实体:

public class Phase
{
    public int Id { get; set; }

    [Required]
    [MaxLength(50)]
    public String Name { get; set; }

    [MaxLength(800)]
    public String Description { get; set; }

    [Required]
    public PhaseCategory PhaseCategory { get; set; }
}

and

public class PhaseCategory
{
  public int Id { get; set; }

  [MaxLength(50)]
  public String Name { get; set; }
}

and I created the following DTO for the Rest Api Call /api/Phases我为 Rest Api Call /api/Phases 创建了以下 DTO

public class PhaseReadDTO
{
    public int Id { get; set; }

    public String Name { get; set; }

    public String Description { get; set; }

    public int PhaseCategoryId { get; set; }
}

The issue I have is that in order to make PhaseCategoryId available, I need to query in the following way:我遇到的问题是,为了使 PhaseCategoryId 可用,我需要通过以下方式进行查询:

var phase = _dbContext.Phases.Include(pc => pc.PhaseCategory).ToList();
return Ok(_mapper.Map<IEnumerable<PhaseReadDTO>>(phase));

That means that behind the scenes, EF is doing an INNER JOIN that is not needed这意味着在幕后,EF 正在执行不需要的 INNER JOIN

SELECT [p].[Id], [p].[Description], [p].[Name], [p].[PhaseCategoryId], [p0].[Id], [p0].[Name]  
    FROM [Phases] AS [p]  
    INNER JOIN [PhaseCategories] AS [p0] ON [p].[PhaseCategoryId] = [p0].[Id]

But when I do但是当我这样做时

var phase = _dbContext.Phases.ToList();
return Ok(_mapper.Map<IEnumerable<PhaseReadDTO>>(phase));

The query is what I expect查询是我所期望的

SELECT [p].[Id], [p].[Description], [p].[Name], [p].[PhaseCategoryId]  
            FROM [Phases] AS [p]

But the PhaseCategoryId is not populated in the response.PhaseCategoryId中未填充PhaseCategoryId

I guess you have something like the following line in your mapping configuration -我猜您的映射配置中有类似以下行的内容-

.ForMember(d => d.PhaseCategoryId, opt => MapFrom(s => s.PhaseCategory.Id))

Right?对?

Since you don't have a property called PhaseCategoryId in your Phase model, you are forcing yourself to load the PhaseCategory property instead to make the mapping happen, and the -由于您的Phase模型中没有名为PhaseCategoryId的属性,因此您强制自己加载PhaseCategory属性来进行映射,并且 -

Include(pc => pc.PhaseCategory)

part of your query is causing the Inner Join.您的查询的一部分导致内部联接。

Add the foreign key property -添加外键属性 -

public int PhaseCategoryId { get; set; }

in your Phase model and define the mapping configuration as simply -在您的Phase模型中并将映射配置定义为简单的 -

CreateMap<Phase, PhaseReadDTO>();

Then you can query without the Include part and still have the PhaseCategoryId in the response.然后,您可以在没有Include部分的情况下进行查询,并且响应中仍然包含PhaseCategoryId

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM