Sander
Sander

Reputation: 73

Protect property value from changing after first creation Entity Framework Code First

What is the best way to prevent a property from changing after it was added to the database?

I know I can do it by tracking state when I am actually using the DbContext in the application. But then it's up to the programmer.

I would like this to be included in a DbContext override or inside the model configuration. Then it would work automatically and reject the change when someone tries to update the property.

One way to solve it would be by overriding ValidateEntity and check it there, but I am wondering if this is the best solution

Upvotes: 1

Views: 610

Answers (2)

Daniel Leiszen
Daniel Leiszen

Reputation: 1897

You can put it in the model by making the property setter private. As far as I know EF maps private properties as well. Or you can create a public property (ignored in map) based on a private property (mapped) and put the logic there. If the model is not in your hand then it should be in the context as you mentioned. ValidateEntity sounds to be a right place but honestly I have no experience doing such thing.

EDIT: I tryied the following

public class Entity
{
    public int Id { get; set; }
    public string Code { get; private set; }

    public string MyCode 
    { 
        get { return this.Code; }
        set
        {
            if (string.IsNullOrEmpty(this.Code))
            {
                this.Code = value;
            }
        }
    }
}

And in the context OnModelCreating

modelBuilder.Entity<Entity>()
    .ToTable("dbo.Entity")
    .HasKey(s => s.Id);

modelBuilder.Entity<Entity>()
    .Property(s => s.Code)
    .IsRequired();

modelBuilder.Entity<Entity>()
    .Ignore(s => s.MyCode);

And it works.

Upvotes: 1

Moho
Moho

Reputation: 16563

Implement the property in your entity class with your own backing variable (old school) and a flag denoting whether or not the property has already been set once:

    private DateTime _created;
    private bool _createdSet = false;

    public DateTime Created 
    {
        get
        {
            return _created;
        }
        set
        {
            if (_createdSet)
            {
                throw new InvalidOperationException("Property 'Created' cannot be changed once set");
            }

            _createdSet = true;
            _created = value;
        }
    }

Upvotes: 1

Related Questions