Entity framework 接收字典<;int,string>;从linq到实体?

Entity framework 接收字典<;int,string>;从linq到实体?,entity-framework,linq-to-entities,Entity Framework,Linq To Entities,问题的继续 但现在不是array=>Dictionary 城市类型是字典 var sites = (from country in db.Countries select new { Country = country.Title, Cities = country.Cities.Sele

问题的继续

但现在不是array=>Dictionary 城市类型是字典

 var sites = (from country in db.Countries
                        select new
                        {
                            Country = country.Title,
                            Cities = country.Cities.Select(m => m.Title)
                        })
                        .AsEnumerable()
                        .Select(country => new SitiesViewByUser()
                        {
                            Country = country.Country,
                            City = country.Cities.ToArray()
                        });
更新:

public class SitiesViewByUser
    {
        public string Country { get; set; }
        public Dictionary<int, string> City { get; set; }
    }
public class SitiesViewByUser
{
公共字符串国家{get;set;}
公共字典城市{get;set;}
}
您可以使用从LINQ序列创建字典

第一部分是关键,第二部分是价值,例如

.Select(country => new SitiesViewByUser()
{
    Country = country.Country,
    City = country.Cities.ToDictionary(c => c, c => c);
});
这假设
SitiesViewByUser
上的
City
定义为
Dictionary

不过,你的LINQ相当混乱。您正在创建一个匿名类型,该类型假定为塑造一个
国家
,但其上有一个
国家
属性,实际上是该国家的
标题
(这是该国家的名称吗?)

您还有一个城市
标题的集合
,因此我不确定您将在
城市
词典中对
SitiesViewByUser
类型使用什么值

还有,什么是SITE\

更新

你可以这样做:

var countries = (from country in db.Countries
   select new
   {
     Title = country.Title,
     CityIds = country.Cities.Select(c => c.Id),
     CityTitles = country.Cities.Select(c => c.Title)
   }).AsEnumerable();

// You have a collection of anonymous types at this point, 
// each type representing a country
// You could use a foreach loop to generate a collection 
// of SitiesViewByUser, or you could use LINQ:

var sitiesViewByUsers = countries.Select(c => new SitiesViewByUser
   {
      Country = c.Title,
      City = c.CityIds.Zip(c.CityTitles, (k, v) => new { Key = k, Value = v })
               .ToDictionary(x => x.Key, x => x.Value)
   };
或者,为什么不将
SitiesViewByUser
类型更改为:

public class SitiesViewByUser
{
    public string Country { get; set; }
    public IEnumerable<City> Cities { get; set; }
}

SitiesViewByUser上城市属性的定义是什么?字典的int键来自哪里?这是这个城市的主键吗?您在初始LINQ to Entities查询中没有检索到此项。
var sitiesViewByUsers = db.Countries.Select(c => new SitiesViewByUser
  {
    Country = c.Title,
    Cities = c.Cities
  });