我有一个 CRUD 存储库作为休耕:
public class CrudRepository<T> : ICrudRepository<T>
where T : class, IUnique
{
static DataContext db = new DataContext();
protected DataContext DataContext { get { return db; } }
public virtual IQueryable<T> GetAll()
{
return db.GetTable<T>();
}
public virtual void Add(T item)
{
db.GetTable<T>().InsertOnSubmit(item);
}
public virtual void Save()
{
db.SubmitChanges();
}
public virtual T Get(int id)
{
return GetAll().FirstOrDefault(t => t.Id.Equals(id));
}
}
我为所有实例关闭存储库使用静态数据上下文。我想更改外键实体,所以我尝试休闲解决方案:
CrudRepository<Employee> employeeRepository = new CrudRepository<Employee >();
Employee employee = employeeRepository.Get(employeeId)
employee.OfficeId = officeId;
employeeRepository.Save();
但它抛出了休闲异常:
ForeignKeyReferenceAlreadyHasValueException
所以我尝试使用第二种解决方案:
CrudRepository<Employee> employeeRepository = new CrudRepository<Employee >();
Employee employee = employeeRepository.Get(employeeId)
employee.Office = new CrudRepository<Office>().Get(officeId);
employeeRepository.Save();
但它会抛出异常消息:
已尝试附加或添加一个不是新的实体,可能是从另一个 DataContext 加载的
我能做些什么?问题是什么?