entity-framework - 从linq到实体接收Dictionary <int,string>?

标签 entity-framework linq-to-entities

问题How get array in linq to entity?的延续

但现在不是数组=>字典
城市类型为字典

 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; }
    }

最佳答案

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

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

.Select(country => new SitiesViewByUser()
{
    Country = country.Country,
    City = country.Cities.ToDictionary(c => c, c => c);
});

假设City上的SitiesViewByUser定义为Dictionary<string, string>
但是您的LINQ令人相当困惑。您正在创建一个匿名类型,假设其形状为Country,但是上面具有Country属性,该属性实际上是该国家/地区的Title(国家名称?)。

您也仅收集了城市Titles,因此我不确定要在City类型的SitiesViewByUser字典中使用什么值。

另外,什么是贴帖? :\

更新

您可以执行以下操作:
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; }
}

然后,您可以做(使用流利的语法):
var sitiesViewByUsers = db.Countries.Select(c => new SitiesViewByUser
  {
    Country = c.Title,
    Cities = c.Cities
  });   

关于entity-framework - 从linq到实体接收Dictionary <int,string>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9454107/

相关文章:

c# - "A lambda expression with a statement body cannot be converted to an expression tree"

c# - 找不到 Entity Framework ADO.NET Sql.Data.Client 提供程序

c# - EF 5.0 和动态连接字符串?

c#-4.0 - Entity Framework 和强制内连接

Linq to Entity Framework 返回仅包含子集子集或空集合的父级列表

c# - Linq to Entities 查询可空数据类型

c# - 如何将 SQL 'LIKE' 与 LINQ to Entities 一起使用?

c# - 使用 linq 和 Entity Framework 构建嵌套表达式

c# - Entity Framework 代码第一列名称问题

sql-server - 首先使用实体​​框架数据库强制 DateTime