Object oriented design is all about encapsulation. A category supplies strategies to govern its knowledge and solely permits manipulation that retains the objects’ state appropriate. That works positive in idea, however in actual life objects must be loaded/materialized from a database and this often implies that property setters should be public. But not with Entity Framework Core! Entity Framework Core makes use of some reflection magic to entry the behind the scenes non-public properties. So it’s now doable to jot down “actual” object oriented entities and persist them to the database.

Adding a traditional entity class, with none concerns taken to persistence works completely effectively with EF Core.

public class MyEntity
  public MyEntity(string title)
    Name = title;
  public int Id { get; non-public set; }
  public string Name { get; non-public set; }
  public void Rename(string newName)
    Name = newName;

There are some restrictions which can be in impact although. So it’s endorsed to make some small changes to the entities.

The first restriction is that when utilizing a constructor that takes parameters it should be parameters that EF can bind to a property. Changing the title of the title parameter to one thing else breaks issues:

Unhandled Exception: System.InvalidOperationException: No appropriate constructor discovered for
entity sort 'MyEntity'. The following parameters couldn't be certain to properties of
the entity: 'foo'.

Even although the names match, there’s a downside with having entity framework name a constructor with enterprise logic when loading knowledge from the database. It is best so as to add a parameterless constructor that EF can use to create objects behind the scenes. It may even be non-public.

To summarize EF Core is TOTALLY AWESOME. Thanks to this characteristic it brings again the facility of object orientation and encapsulation.

An entire working code instance is out there within the EfCorePrivate repo on my GitHub Account.

Posted in C# on 2018-06-06 | Tagged Entity Framework Core

Source link