Click here to Skip to main content
15,886,362 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
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:

C#
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.

Try this:

C#
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();
}
 
Share this answer
 
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.
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:
C#
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();
 
Share this answer
 
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)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900