Click here to Skip to main content
14,176,386 members
Rate this:
 
Please Sign up or sign in to vote.
See more: , +
I am trying to do a simple select where statement to get the name of country where the code alfa2 = country[i] in a loop.

What I have tried:

OFFERS_COUNTRIES c = new OFFERS_COUNTRIES();
    for (int i = 0; i < countryId.Length; i++)
       {
          var nnn = from e in db.COUNTRIES where e.alfa2 == countryId[i] select e.countryName;
          c.country_name = nnn.ToString();

          db.OFFERS_COUNTRIES.Add(c);
          db.SaveChanges();
        }

I receive the exception in this line:
c.country_name = nnn.ToString();
What is the problem?
Posted
Updated 13-Mar-18 6:32am
Comments
#realJSOP 12-Mar-18 14:44pm
   
BTW, your tags for this question were a little over the top. All you really needed was C#, LINQ, and Entity Framework. the rest are irrelevant to the question.
Laxmidhar tatwa technologies 12-Mar-18 22:40pm
   
C.country_name = nnn.first().tostring();
TempoClick 13-Mar-18 6:31am
   
@Laxmidhar thanks. This is what I needed.
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 1

Try this:

for (int i = 0; i < countryId.Length; i++)
{
    var countryID = countryId[i]; //<-- removes array reference from the linq query
    var nnn = from e in db.COUNTRIES where e.alfa2 == countryID select e.countryName;
    c.country_name = nnn.ToString();

    db.OFFERS_COUNTRIES.Add(c);
    db.SaveChanges();
}
   
v2
Comments
Maciej Los 12-Mar-18 13:59pm
   
5ed!
TempoClick 13-Mar-18 6:30am
   
@JohnSimmons Thanks for the reply. This approach is missing what @Laxmidhar commented above. Without .first() it would return the SQL query instead of the variable.
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 2

It would almost certainly be more efficient to retrieve the list of country names in a single query, and to only save the changes after adding all of the offers to the context:
var countries = db.COUNTRIES
    .Where(e => countryId.Contains(e.alfa1))
    .Select(e => e.countryName)
    .AsEnumerable()
    .Select(name => new OFFERS_COUNTRIES 
    {
        country_name = name
    });

db.OFFERS_COUNTRIES.AddRange(countries);
db.SaveChanges();
   
Comments
Maciej Los 13-Mar-18 13:34pm
   
If i could add double 5...

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


Advertise | Privacy | Cookies | Terms of Service
Web01 | 2.8.190525.1 | Last Updated 13 Mar 2018
Copyright © CodeProject, 1999-2019
All Rights Reserved.
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100