English 中文(简体)
人口结构
原标题:Cast to a type inside a LINQ To Entity Query

我有这份准则。

var Cities= (from city in AllCities
    where (city.NumberOfCitizens > 1000)
    select new
    {
        Mayor= (from mayor in AllMayors where mayor.CityKey == city.Key select mayor),
        Name = city.Name,
        Country = city.Country,
        Key = city.Key
        }).ToList();

我从我拥有的1 000名公民的城市中挑选市长、名称、国家和关键人物。

<代码>Mayor为一类,具有2种特性<编码> 规范第一Name和<编码> 规范上层<<>。

现在,我想再问一下:(这是第一次查询的结果)和LastName的城市市长们,这些城市具有关键和强力;20

var Result= (from city in Cities
    where (city.Key> 20)
    select new
    {
        MayorFirstName = city.Mayor.FirstName,
        MayorLastName = city.Mayor.LastName,
        City = city.Name
        }).ToList();

问题是,我会发现该市的错误。 市长并不包含<代码>FirstName和

我试图将它带给在座的市长们:

Mayor= (Mayor)(from mayor in AllMayors where mayor.CityKey == city.Key select mayor),
.......

申请通常会形成和启动,但是,我无法在LINQ问询中找到一种类型的错误。

我如何解决这一问题? 是否有办法在盘点内投放,有其他解决办法。

感谢任何帮助

最佳回答

您询问的这一部分结果为:NOT, 单一<条码>。

Mayor = (from mayor in AllMayors where mayor.CityKey == city.Key select mayor)

Change this line to:

Mayor= (from mayor in AllMayors where mayor.CityKey == city.Key select mayor).FirstOrDefault()

然后,市长的财产将是一个单独的<代码>Mayor例。

请注意,如果无市长,则使用<代码>FirstOrDefault,将返回null,而First(>则不会发现任何市长。 两者的选择取决于您的情况。

问题回答

各位希望选择一个单一项目,而不是向市长指定一个<条码>电子计算和编号;Mayor>。 使用数字。 第一(a)项:

Mayor = AllMayors.FirstOrDefault(mayor => mayor.CityKey == city.Key)

例如:

var Cities= (from city in AllCities
             where (city.NumberOfCitizens > 1000)
             select new
             {
               Mayor= AllMayors.FirstOrDefault(mayor => mayor.CityKey == city.Key),
               Name = city.Name,
               Country = city.Country,
               Key = city.Key
             }).ToList();




相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签