I am not able to select a few direct columns along with a few specific columns in the One to One relationship table in the Entity Framework with Fluent 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;
}
I want to get a JSON object response like this:
{
"Id": 1,
"FirstName": "John",
"Address": {
"AId": 1,
"City": "San Francisco",
"State": {
"Sid": 1,
"Name": "California"
}
}
}
I am currently doing
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();
Can I include the field in that inner select of one-to-one navigation reference. ?
Is it the right way to select inner one-to-one relationship columns..?
How do I select the columns as exactly as my JSON response?
CodePudding user response:
If you do not have appropriate DTO, better project to anonymous 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();
Note that AsNotracking()
is not needed if you have custom projection via Select
, EF do not track custom objects.