Let’s assume I have a file with multiple rows each representing a Person, the Person entity has an identity column that is also the primary key. Assuming that a Person can be repeated in the file, if it is, perhaps I want to do a last entry wins scenario. In the example below I use a repository to retrieve a person from the database by the social security number. The issue is that when the same SSN shows up again in the file, the repository still returns a null, even though technically that person with that SSN has already been added to the context (SaveChanges hasn’t been called yet). I realize I can work around this by tracking myself which Person objects have already been added. I am wondering what is the best practice for this scenario.
Thanks.
foreach(row in fileRows)
{
Person person = personRepository.GetBySSN(row.SSN);
if(person == null)
{
//insert logic
}
else
{
//update logic
}
}
personRepository.SaveChanges();
I haven’t found anything regarding best practices so I’ll post my solution. I know many other posts refer to the fact that the EF context provides mechanisms for looking into it and seeing if a particular entity is in attached state. Being that I work through repositories (my business layer has no direct access to the EF context), my choice is either offloading this sort of logic into the repository, or attempt to solve it in the business layer. My feeling is that this task is really a business concern and not a data access layer concern.