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

Med*_*tor 7 linq-to-entities entity-framework

问题的延续如何将linq中的数组转换为实体?

但现在不是array => Dictionary City类型是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()
                        });
Run Code Online (Sandbox Code Playgroud)

更新:

public class SitiesViewByUser
    {
        public string Country { get; set; }
        public Dictionary<int, string> City { get; set; }
    }
Run Code Online (Sandbox Code Playgroud)

dev*_*tal 9

您可以使用ToDictionary从LINQ序列创建字典.

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

.Select(country => new SitiesViewByUser()
{
    Country = country.Country,
    City = country.Cities.ToDictionary(c => c, c => c);
});
Run Code Online (Sandbox Code Playgroud)

这假设Cityon SitiesViewByUser定义为Dictionary<string, string>

你的LINQ虽然很混乱.你正在创建一个匿名类型,被设计为一个Country,但它有一个Country属性,这实际上是Title国家(这个国家的名称?).

你也有一个只有城市的集合Titles,所以我不确定你将City在你的SitiesViewByUser类型的词典中使用什么价值.

还有什么是Sitie?:\

更新

你可以这样做:

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)
   };
Run Code Online (Sandbox Code Playgroud)

或者,为什么不将SitiesViewByUser类型更改为:

public class SitiesViewByUser
{
    public string Country { get; set; }
    public IEnumerable<City> Cities { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

然后你可以做(​​使用流利的语法):

var sitiesViewByUsers = db.Countries.Select(c => new SitiesViewByUser
  {
    Country = c.Title,
    Cities = c.Cities
  });   
Run Code Online (Sandbox Code Playgroud)