如何 select 一对一关系中的特定列 table 以及 Entity Framework Fluent API 中的几个直接列

How to select specific columns in one-to-one relationship table along with few direct columns in Entity Framework Fluent API

我无法 select 在一对一关系 table 中 Entity Framework 中的一些直接列和一些特定列 API .

public class Employee
{
    public int id;
    public string FirstName;
    public string LastName;
    public Address address;
}

public class Address
{
    public int AId;
    public string City;
    public string PinCode;
    public string District;
    public State State;
}

public class State
{
    public int Sid;
    public string Name;
    public string CapitalCity;
}

我想得到这样的 JSON 对象响应:

{
  "Id": 1,
  "FirstName": "John",
  "Address": {
    "AId": 1,
    "City": "San Francisco",
    "State": {
      "Sid": 1,
      "Name": "California"
    }
  }
}

我正在做

this.context.Employees
            .Select(employee => new Employee
                                    {
                                        Id  = employee.Id;,
                                        FirstName  = employee.FirstName;
                                        Address = employee.Address.select(*I am struggling here*);
                                        State = employee.Address.State.select(*I am struggling here*);
                                        Id  = employee.Id;
                                    })
            .AsNoTracking()
            .FirstOrDefaultAsync();

我可以在一对一导航参考的内部 select 中包含该字段吗? ?

这是 select 内部一对一关系列的正确方法吗?

如何 select 列与我的 JSON 回复完全一致?

如果您没有合适的 DTO,最好匿名 class:

var result = his.context.Employees
    .Select(employee => new
    {
        employee.Id,
        employee.FirstName,
        Address = new 
        { 
            employee.Address.AId,
            employee.Address.City,
            State = new 
            {
                employee.Address.State.Sid,
                employee.Address.State.Name
            }
        }
    })
   .FirstOrDefaultAsync();

请注意,如果您通过 Select 进行自定义投影,则不需要 AsNotracking(),EF 不跟踪自定义对象。