gpt4 book ai didi

entity-framework - 如何确保在 Entity Framework 中使用存储库模式时创建代理?

转载 作者:行者123 更新时间:2023-12-03 07:23:41 24 4
gpt4 key购买 nike

我的 SurveyController 类中有这个方法:

public ActionResult AddProperties(int id, int[] propertyids, int page = 1)
{
var survey = _uow.SurveyRepository.Find(id);
if (propertyids == null)
return GetPropertiesTable(survey, page);

var repo = _uow.PropertySurveyRepository;

propertyids.Select(propertyid => new PropertySurvey
{
//Setting the Property rather than the PropertyID
//prevents the error occurring later
//Property = _uow.PropertyRepository.Find(propertyid),
PropertyID = propertyid,
SurveyID = id
})
.ForEach(x => repo.InsertOrUpdate(x));
_uow.Save();

return GetPropertiesTable(survey, page);
}

GetPropertiesTable 重新显示 Properties,但 PropertySurvey.Property 被标记为虚拟,并且我已使用 new 运算符创建了实体,因此从未创建支持延迟加载的代理,并且当我访问它时它为 null。当我们可以直接访问 DbContext 时,我们可以使用 Create 方法 explicitly create the proxy 。但我这里有一个工作单元和存储库模式。我想我可以通过repository.Create方法公开context.Create方法,然后我需要记住在添加实体时使用它而不是new运算符。但将问题封装在我的 InsertOrUpdate 方法中不是更好吗?有没有某种方法可以检测到所添加的实体在应该是代理时不是代理并替换代理?这是我的基本存储库类中的 InsertOrUpdate 方法:

    protected virtual void InsertOrUpdate(T e, int id)
{
if (id == default(int))
{
// New entity
context.Set<T>().Add(e);
}
else
{
// Existing entity
context.Entry(e).State = EntityState.Modified;
}
}

最佳答案

基于 qujck 提供的答案。以下是您无需使用自动映射器即可完成此操作的方法:

编辑以始终检查代理 - 不仅仅是在插入期间 - 正如评论中所建议的

再次编辑以使用不同的方式检查代理是否已传递到该方法。改变技术的原因是当我引入一个从另一个继承的实体时遇到了问题。在这种情况下,继承的实体即使是代理,也可能无法通过 entity.e.GetType().Equals(instance.GetType() 检查。我从 this answer 获取了新技术

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

public abstract class ModelBase
{
public int ID { get; set; }
}

关于entity-framework - 如何确保在 Entity Framework 中使用存储库模式时创建代理?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16736143/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com