LINQ实体中不支持LINQ表达式节点'arrayindex'。
问题描述:
我正在尝试做一个简单的选择where语句来获取代码alfa2 = country [i]在循环中的国家名称。
我尝试过:
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();
有什么问题?
答
试试这个:
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();
}
在单个查询中检索国家/地区名称列表几乎肯定会更有效,并且只在添加后保存更改上下文中的所有要约:
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();