У меня есть общий метод, который обновляет или вставляет и сущность. Я не понимаю цели заявления if здесь. Комментарий говорит мне, для чего он нужен, но мне не ясно.
Почему пространство имен сверяется с System.Data.Entity.DynamicProxies. Я думал, что все сущности, извлеченные через структуру сущностей, будут в этом пространстве имен? И зачем нам проверять базовый тип на ноль?
public virtual T InsertOrUpdate(T e)
{
DbSet<T> dbSet = Context.Set<T>();
DbEntityEntry<T> entry;
if (e.GetType().BaseType != null
&& e.GetType().Namespace == "System.Data.Entity.DynamicProxies")
{
//The entity being added is already a proxy type that supports lazy
//loading - just get the context entry
entry = Context.Entry(e);
}
else
{
//The entity being added has been created using the "new" operator.
//Generate a proxy type to support lazy loading and attach it
T instance = dbSet.Create();
instance.ID = e.ID;
entry = Context.Entry(instance);
dbSet.Attach(instance);
//and set it's values to those of the entity
entry.CurrentValues.SetValues(e);
e = instance;
}
entry.State = e.ID == default(int) ?
EntityState.Added :
EntityState.Modified;
return e;
}