通用插入或更新方法

时间:2018-10-29 01:57:09

标签: c# .net entity-framework

我有一个更新或插入实体的通用方法。我在这里不了解if语句的目的。该评论告诉我它的用途,但我不清楚。

为什么要根据System.Data.Entity.DynamicProxies检查名称空间。我以为通过实体框架检索的所有实体都将在此命名空间下?为什么我们要检查基本类型是否为null?

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;
}

0 个答案:

没有答案