I have two models in LINQ to SQL. First is Employee and the second is Position.
There is Position data that I already inserted in Position table. This data will be referenced by Employee model.
Position {
int id, //auto increament
string name,
string description,
}
Employee {
int id,
string name,
Position position,
}
The logic when I want to create employee is:
- I Crate EmployeCreate and Assign employee name, and position ID
- Find the position by Id using position repository.
- Create Employee model assign the founded position model from step two
- Insert the employe using employee repository and submit changes
I think my steps is correct, But The founded positions is insert in to database again, normally It is not inserted because the data already exists in the database.
My snippet service as follows:
EmployeService {
//property and constructor
AddEmployee(EmployeeCreate command) {
var employee = EmployeeFactory.Create(command);
var possition = _positionRepository.GetById(command.possitionId);
using (var tx = new TransactionScope())
{
employee.Position = possition;
_employeeRepository.InsertOnSubmit(employee);
_employeeRepository.SubmitChanges();
tx.Complete();
}
}
}
EDIT
I create generic Linq repository. Employee and Position is extends the generic Linq repository.
public class LinqRepository<T> : IRepository<T>, IRepository where T : class
{
protected readonly DataContext _dataContext;
public LinqRepository(IDataContextProvider dataContextProvider)
{
_dataContext = dataContextProvider.DataContext;
}
}
You shouldn’t need the TransactionScope here unless you are trying to submit changes across multiple contexts. SubmitChanges internally creates a transaction for the request to cover the multiple insert/update/delete operations requested as part of the submitchanges. The only time you need to explicitly manage the context is when you have multiple context/connections that are spanned by the call.
The behavior you are seeing indicates that the Position may be fetched by a context other than the one that you are using when inserting the employee into the _employeeRepostiory.