Saulo Vallory
Saulo Vallory

Reputation: 979

How to disable insert in Entity Framework?

Is there any way do disable the insertion of an Entity in Entity Framework?

I'm using DDD and, on a specific bounded context, some required database fields of the users table doesn't make sense (inside this context). So, I want to remove them from the User entity, but in doing so I loose the ability to save a new user to database. Which is ok, since, in this context, I shouldn't create users.

My first thought was to disable the insertion (but allow updates) on the User Entity.

Is it feasible? Or, is there another solution to this situation?

Upvotes: 0

Views: 680

Answers (1)

Ladislav Mrnka
Ladislav Mrnka

Reputation: 364409

You cannot disable insertion but you can find if any entity is marked for insertion and fire exception in such case.

The best place to do such handling is in override of SaveChanges method:

public override int SaveChanges(SaveOptions options)
{
    if (ObjectStateManager.GetObjectStateEntries(EntityState.Added)
                          .Where(e => !e.IsRelationship)
                          .Select(e => e.Entity)
                          .OfType<User>()
                          .Any())
    {
        throw new InvalidOperationException("User cannot be inserted");
    }

    return base.SaveChanges(options);
}

This is runtime behavior but because EF doesn't differ between modification operations (all are inside single SaveChanges) you cannot detect inserting at compile time.

Upvotes: 2

Related Questions