1

I am trying to create an abstract class which will contain properties and every entity in my solution will inherit this properties.

I do want that abstract class properties to be restricted from any user modification except the changes which are made by code.

What I want to achieve:

public abstract class SystemEntityBase
{
    /// <summary>
    /// Gets the date when entity was created.
    /// </summary>
    public DateTime Created { get; } = DateTime.UtcNow;

    /// <summary>
    /// Gets the date when entity was last active in the system.
    /// </summary>
    public DateTime LastActive { get; } = DateTime.UtcNow;
}

Because I am using read-only property, the EntityFrameworkCore will not add this fields to my database table when auto-generating the migration scripts.

I am curios what are possible solutions to restrict properties in my case while also create the database columns?

2 Answers2

2

You should be able to use init only properties if you can use c# 9.0.

jjxtra
  • 20,415
  • 16
  • 100
  • 140
  • Init properties require c# 9 **and** either .net 5 or a manual copy of the necessary mod-req type. Definitely worth a try - I'm just saying it isn't *just* c# 9 that is needed. – Marc Gravell Dec 25 '20 at 19:08
  • 1
    But user still will be able to set the property value by `new SomeEntity {Created = ....}` which is not what OP wants as I understand. – Guru Stron Dec 25 '20 at 19:14
1

If I understood problem correctly - you can try using Backing Fields. For your Created property it can look something like that (for some reason using BackingFieldAttribute didn't work for me with my test SQLite and postgres setups, but fluent API did the trick):

public class SomeEntity
{
    public DateTime Created => _created

    private DateTime _created = DateTime.UtcNow;    
}

And in OnModelCreating(ModelBuilder modelBuilder):

 modelBuilder.Entity<SomeEntity>()
     .Property(b => b.Created)
     .HasField("_test");

Also it is possible to remove the need to setup all SomeEntity's by hand via some reflection magic.

Guru Stron
  • 102,774
  • 10
  • 95
  • 132