【发布时间】:2014-02-23 22:17:06
【问题描述】:
我有一个禁用延迟加载的数据库上下文。我正在使用急切加载来加载我的所有实体。我无法更新多对多关系。
这是存储库。
public class GenericRepository<TEntity> : IGenericRepository<TEntity>
where TEntity : class
{
... other code here...
public virtual void Update(TEntity t)
{
Set.Attach(t);
Context.Entry(t).State = EntityState.Modified;
}
...other code here...
}
这是用户模型。
public partial class User
{
public User()
{
this.Locks = new HashSet<Lock>();
this.BusinessModels = new HashSet<BusinessModel>();
}
public int UserId { get; set; }
public string Username { get; set; }
public string Name { get; set; }
public string Phone { get; set; }
public string JobTitle { get; set; }
public string RecoveryEmail { get; set; }
public Nullable<double> Zoom { get; set; }
public virtual ICollection<Lock> Locks { get; set; }
public virtual ICollection<BusinessModel> BusinessModels { get; set; }
}
如果我修改业务模型集合,它不会不保存业务模型集合,尽管我已附加整个实体。
Worker.UserRepository.Update(user);
我不确定发生了什么。我不想仅仅为了更新多对多关系而破坏我的通用存储库/工作单元模式。
编辑 2: 我已经完成了这项工作……但它与我想要的模式截然不同。拥有硬实现意味着我需要为每种类型创建一个方法,这些类型具有多对多关系。我现在正在调查是否可以将其设为通用方法。
编辑 3: 所以我之前的实现并没有像我想象的那样工作。但是现在,我有一个稍微有效的实现。如果有人愿意帮助我,这样我就可以继续前进,我会永远爱你。
public virtual void Update(TEntity updated,
IEnumerable<object> set,
string navigationProperty,
Expression<Func<TEntity, bool>> filter,
Type propertyType)
{
// Find the existing item
var existing = Context.Set<TEntity>().Include(navigationProperty).FirstOrDefault(filter);
// Iterate through every item in the many-to-many relationship
foreach (var o in set)
{
// Attach it if its unattached
if (Context.Entry(o).State == EntityState.Detached)
// Exception "an object with the same key already exists"
// This is due to the include statement up above. That statement
// is necessary in order to edit the entity's navigation
// property.
Context.Set(propertyType).Attach(o);
}
// Set the new value on the navigation property.
Context.Entry(existing).Collection(navigationProperty).CurrentValue = set;
// Set new primitive property values.
Context.Entry(existing).CurrentValues.SetValues(updated);
Context.Entry(existing).State = EntityState.Modified;
}
然后我这样称呼它:
Worker.UserRepository.Update(user, user.BusinessModels, "BusinessModels", i => i.UserId == user.UserId, typeof (BusinessModel));
非常混乱,但它让我可以更新与泛型的多对多关系。当我去附加已经存在的新值时,我的大问题是例外。由于包含语句,它们已经被加载。
这行得通:
这不是:
【问题讨论】:
-
它不是那样工作的。您需要单独更新 BusinessModel。
-
我有,但是不保存两者的关系。我需要更新用户内部的业务模型集合还是调用业务模型存储库并将其保存在那里?
-
单独更新关系。
-
我知道我需要更新关系......我该怎么做?
-
请关注this example
标签: c# entity-framework generics