Backing fields are an option, however I don't recommend them for PKs given you are likely going to want to be able to select data by PK and the PK won't be exposed by the entity. For instance you might want to check child data using:
var employeesInDepartment = context.Employees
.Where(x => x.Department.DepartmentId == departmentId)
.ToList()
or
var employeesInDepartment = context.Departments
.Where(x => x.DepartmentId == departmentId)
.SelectMany(x => x.Employees)
.ToList();
This won't be available if your Department ID is completely hidden. You can leverage .Find
which will use the mapped PK, however, this is less practical because Find
will always load the entity, where Select
can be more selective about the data you want to retrieve. You'll also want PKs to send to the UI so that you can associate data coming back to their respective entities on the return trip. For instance when I create a new employee, it will be associated to a department. I send back a DepartmentID to associate, not disconnected entities. Sending entities is a performance and security trap, and even if you did want to serialize entities across, private backing fields would not be transferred so a Department entity coming back would lack any PK, rendering it useless.
Instead of trying to hide the property, you can guard the Setters by making them Private.
public class Department
{
public int DepartmentId { get; private set; }
// ...
public virtual ICollection<Employee> Employees { get; private set; } = new List<Employee>();
}
This way you can still take advantage of accessing these properties in Linq expressions without implying they can be set. Collection references should never expose setters to avoid issues where someone tries clearing a child collection by setting the collection to a new List.
Note: This solution still will not allow you to receive entities from the client because the private setter will prevent deserialization. This is a good thing, as it will help ensure that your project does get corrupted to accept entities from the client. I cover the implications of this here.