Peter Lea
Peter Lea

Reputation: 1751

Entity Framework OnChanging protect primary keys

I have a problem with implementing a check that stops a developer from manually or programmatically updating the primary key in code after the initial creation.

 partial class User
{
    public User()
    {
        this.UserId = sGuid.NewSGuid(sGuidType.SequentialAtEnd);
    }

    partial void OnUserIdChanging(Guid value)
    {
        //throw if its an edit...
        throw new DbEntityValidationException("Cannot mutate primary key");
    }

}

This works fine if i'm editing/updating an object, but it won't actually let me create a new Entity in the first place. Is there any way I can check at this point to see if its a new entity or an existing entity?

Thanks in advance, Pete

UPDATE:

Typical I always find the answer after I post -_- ! Thanks for your answers guy, I'll mark one of yours as a correct answer as they were valid alternatives.

if (this.EntityState != System.Data.EntityState.Detached)
{
    throw new DbEntityValidationException("Cannot mutate primary key");
}

Upvotes: 0

Views: 173

Answers (1)

Dennis
Dennis

Reputation: 37770

This problem is usually solved by making primary key setters private or protected:

public class MyEntity
{
  public int Id { get; private set; }
}

If you're using EF designer, just select property in designer and set appropriate access modifier in the property grid - your code generator will do the rest.

Upvotes: 1

Related Questions