5

My domain model and its associations are as follows:

  • Customer has many Regions
  • Region has many Locations

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?

2 Answers 2

6

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();
Sign up to request clarification or add additional context in comments.

Comments

2

Try this

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

if (customer == null)
    customer = new Customer(...);

2 Comments

If you need to ensure that there is at most one record returned you should use SingelOrDefault instead of FirstOrDefault
Thanks for the swift response! That did it as well! :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.