jdl134679 jdl134679 - 29 days ago 14
C# Question

ReadOnly Property that Entity Framework can set

Very basic, yet my Google-fu is failing me.

I have a domain object, say User, that I want the Active property to be read only on. Yet, the property needs to be set via EF(6) when loaded from the database.

Table:

CREATE TABLE Users (
ID INT NOT NULL PRIMARY KEY CLUSTERED,
Active BIT NOT NULL DEFAULT 1
-- other stuff
);


Class:

public class User
{
public int ID { get; set; }
public bool Active { get; set; } // this should be RO

public void Activate() {
Active = true;
this.AddChangelog(ChangeType.Activation, "Activated");
}

public void Deactivate() {
Active = false;
this.AddChangelog(ChangeType.Activation, "Deactivated");
}

// changelogging, etc.
}


Developers should not change
Active
directly, but instead should use the
Activate()
and
Deactivate()
methods. Yet, EF6 needs set
Active
directly so it can instantiate the object.

Architecture (if it matters):


  • User class exists in
    Domain
    project

  • EF6 class configuration is done via
    Data
    project

  • EF6 uses Fluent API configuration (keeps ORM stuff out of my domain project)

  • EF6 does not use DTOs but configures the domain classes directly



Question

How can I enforce (or at least warn) devs not to set
user.Active
? At very least, can I offer some compile-time warning (akin to
[Obsolete]
) to the setter so they get a notice?

Thanks,

Answer

You can use friend assemblies to solve your problem and make it public to your project that you want and make it private to other projects.

[assembly:InternalsVisibleTo("cs_friend_assemblies_2")]
Comments