Finding or creating an object in Entity Framework

c#, entity-framework

Solution

This code

var customer = from c in _data.Customer
               where c.Name == cells[0]
               select c;

Returns all the customers who has the `Name` equals `cells[0]` so the return type will be `IQueryable<Customer>` not a sigle `Customer` (that's why the `customer = new Customer(...)` doesn't work).

What you need is to call `FirstOrDefault` or `SingleOrDefault` (depending on your requirements.) on it if you want to have back one `Customer`.

So this should work

var customer = (from c in _data.Customer
               where c.Name == cells[0]
               select c).SingleOrDefault();

Problem

My domain model and its associations are as follows: - `Customer` has many `Region`s - `Region` has many `Location`s Our client supplies us with a CSV file that has the following columns: - Customer name - Region name - Location name - Latitude - Longitude - ... Based on this information, I have to find or create the customer by name, find or create the region by name, and finally find or update the location by name. I have tried the following: ``` var customer = from c in _data.Customer where c.Name == cells[0] select c; if (customer == null) customer = new Customer(...); ``` I would follow the same pattern for finding or creating/updating the region and location, however, the problem I run into is that the type of the LINQ query cannot be converted to a `Customer`-object on line `customer = new customers();`. I need to reference this `customer` object later so I can't have two separate variables. How would I accomplish this in Entity Framework?

Original source