I am reading data from a Comma-separated Value (CSV) document and saving its contents to a database. Each row in the CSV file contains the following columns:
- Customer ID
- Latitude
- Longitude
Our domain model is as follows:
Customerhas manyLocationsLocation- Latitude
- Longitude
For each row, I am reading the Customer ID and look it up in the database:
var customer = (from c in Context.Customer
where c.ID == id
select c).SingleOrDefault();
If it does not exist, I create one:
if (customer == null)
{
customer = new customers();
customer.ID = id;
}
I do not save it at this point. Next, I create a new Location, and set its customer. Note that this customer may not actually be in the database yet.
Now consider the following: if a customer is not yet in the database, I create one. But I do not save it yet. Now the next row belongs to the same customer that I just created, it is not yet in the database. It will therefore create another customer.
When the time comes to save the graph to database, it will try to save two distinct customers with the same ID and fail.
How can I get Entity Framework to also select from what is in its context, even though it may not be persisted yet?
First of all, you have to attach newly created entities to the context instance.
Second, if you’re using Code First, you can use DbSet.Find method – it can search for entities, which were not saved in store, but were already attached to context, without executing query to the store.