I have a CRUD repository as fallowing:
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));
}
}
I use static data context for all instance off repository. I want to change foreign key entity so i try fallowing solution:
CrudRepository<Employee> employeeRepository = new CrudRepository<Employee >();
Employee employee = employeeRepository.Get(employeeId)
employee.OfficeId = officeId;
employeeRepository.Save();
But it throw fallowing exception :
ForeignKeyReferenceAlreadyHasValueException
So i try fallowing second solution:
CrudRepository<Employee> employeeRepository = new CrudRepository<Employee >();
Employee employee = employeeRepository.Get(employeeId)
employee.Office = new CrudRepository<Office>().Get(officeId);
employeeRepository.Save();
But it throw exception with fallowing message:
An attempt has been made to Attach or Add an entity that is not new, perhaps having been loaded from another DataContext
what can i do? what is the problem?