I’m new to EF 4.1 and try to move some code from to EF 4.1 (code first). Here is some background. I’m managing products for several companies, so I have a table “Product” with a column called “Company”. I need to update (insert if not exist, otherwise update) this table from an Excel file containing products for a given company(let’s say C1). Here is what I’m doing (using proprietary db access code and LINQ) :
- Retrieve all products for company C1 as a list of products
- For each product appearing in Excel:
- Search the loaded list of products if the product from Excel exists already
- If product does not exist then :
- create new product instance
- add product to database
- add product to the list of loaded products
Else - update product in database
That’s pretty straightforward but converting it to EF 4.1 does not seem that easy:
I can easily retrieve and filter all products from the context. I can also easily search for the Excel product in the loaded list. If not present, I can create the product and add it to the context. But how to mimic my “caching” system where I add the newly added product to my list of product loaded in memory (Excel file can contains several times the same product) ? Also when change the entity state and when to do savechanges ?
Christian
Here is a rough outline of how you can do this.
EF caches the loaded entities. You can use Local property to access it. This collection will be modified by EF when you add new entities.