简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM