Reputation: 766
I am currently experiencing a weird problem with EF. Let's say I have the following information in my database. Department ID is a foreign key to the Departments table.
Whenever I make an update to this record by calling the DbContext.Update method it sets the Department ID to null. The only time that it does not do this is when I make a change to the Department ID itself.
var employeeDto = new EmployeeDto
{
Id = 3 // assume that the primary key of this record is 3.
Name = "Motea Dave",
UserId = "123123",
DepartmentId = 3
};
var employee = Mapper.Map<Employee>(employeeDto);
_employeeRepository.Update(employee, employee.Id);
_unitOfWork.SaveChanges(); // When I set my breakpoint here and inspect _employeeRepository I can already see that the DepartmentId has been set to null.
//Employee Repository
public class EmployeeRepository : RepositoryBase<Employee>
{
// Repository code here...
}
//Repository Base
public abstract class RepositoryBase<T> where T : class
{
private readonly IUnitOfWork unitOfWork
public RepositoryBase(IUnitOfWork unitOfWork)
{
this.unitOfWork = unitOfWork;
}
public virtual void Update(T entity, int id)
{
var item = this.Dataset.Find(id);
item.Copy(entity);
item.Id = id;
this.unitOfWork.Context.Update<T>(item); //unitOfWork.Context is basically DbContext of Entity Framework.
}
}
Removing the Update method and calling SaveChanges() directly does not help either.
Upvotes: 0
Views: 70
Reputation: 81503
This seems like an AutoMapper problem and not Entity Framework
var employee = Mapper.Map<Employee>(employeeDto);
If this line sets your DepartmentId
to null, consult your mapping and make sure you haven't ignored the property, or if need be make a mapping for it
Update
It does not. Before executing _
employeeRepository.Update()
I checked the employee variable first and the DepartmentId (3) is there. It becomes null as soon as I execute the _employeeRepository.Update() method which is confusing.
Then its likely with your repository code, it would be extremely unlikely for entity framework to null out a value with an Attach
and saveChanges
However, you will need to put the relevant repository code in your question
Upvotes: 1