Entity Framework Core and Private Properties

Object oriented design is all about encapsulation. A class provides methods to manipulate its data and only allows manipulation that keeps the objects’ state correct. That works fine in theory, but in real life objects need to be loaded/materialized from a database and this usually means that property setters must be public. But not with Entity Framework Core! Entity Framework Core uses some reflection magic to access the behind the scenes private properties. So it is now possible to write “real” object oriented entities and persist them to the database.

Adding a normal entity class, without any considerations taken to persistence works perfectly well with EF Core.

public class MyEntity
{
  public MyEntity(string name)
  {
    Name = name;
  }
 
  public int Id { get; private set; }
  public string Name { get; private set; }
 
  public void Rename(string newName)
  {
    Name = newName;
  }
}
Software Development is a Job – Coding is a Passion

I'm Anders Abel, an independent systems architect and developer in Stockholm, Sweden.

profile for Anders Abel at Stack Overflow, Q&A for professional and enthusiast programmers

Code for most posts is available on my GitHub account.

Popular Posts

Archives

Series

Powered by WordPress with the Passion for Coding theme.