简体   繁体   English

如何在Entity Framework中禁用插入?

[英]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). 我正在使用DDD,并且在特定的有界上下文中,users表的一些必需数据库字段没有意义(在此上下文中)。 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. 所以,我想从User实体中删除它们,但是这样做我失去了将用户保存到数据库的能力。 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: 执行此类处理的最佳位置是覆盖SaveChanges方法:

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. 这是运行时行为,但由于EF在修改操作之间没有差异(所有都在单个SaveChanges ),因此无法在编译时检测插入。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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