Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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,

like image 610
jleach Avatar asked Nov 27 '25 17:11

jleach


1 Answers

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")]
like image 71
MacakM Avatar answered Nov 30 '25 07:11

MacakM



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!