jleach
jleach

Reputation: 7792

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):

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,

Upvotes: 3

Views: 825

Answers (1)

MacakM
MacakM

Reputation: 1820

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")]

Upvotes: 2

Related Questions