无法将类型为'<>f__AnonymousType1`2 [System.Int64,System.String]'的对象强制转换为类型'ConsoleApplication1.Profile'。

5

我非常新于Linq和Entity Framework,我的下面的代码有问题。我得到的错误是:

无法将类型为“<>f__AnonymousType1`2[System.Int64,System.String]”的对象强制转换为类型“ConsoleApplication1.Profile”。

我的代码如下:

static void Main(string[] args)
        {
            ProfileEntitiesContext obj = new ProfileEntitiesContext();
            List<Profile> list = new List<Profile>();
            var test = (from c in obj.Customer
                       join a in obj.Address
                       on c.ProfileId
                       equals a.Customer.ProfileId 
                       select new
                       {
                           CustomerProfileId = c.CustomerProfileId,
                           FirstName = c.FirstName
                   AddressLine1 = a.Line1   
                       }).ToList().Cast<CustomerConfidentialProfile>();

foreach(var cust in test) // Unable to cast object of type  '<>f__AnonymousType1`2
//[System.Int64,System.String]' to type 'ConsoleApplication1.Profile'.
            {
                list.Add(cust);
            }
        }

public class Profile
    {
        int _CustomerProfileId;
        string _FirstName;
        string _AddressLine1;


        public int CustomerProfileId
        {
            get { return _CustomerProfileId; }
            set { _CustomerProfileId = value; }
        }


        public string FirstName
        {
            get { return _FirstName; }
            set { _FirstName = value; }
        }

  public string AddressLine1
        {
            get { return _AddressLine1; }
            set { _AddressLine1= value; }
        }
}

任何帮助都将不胜感激。
3个回答

10

你的问题在于,你使用 new { ... } 语法返回一个匿名类型的LINQ查询结果。

然而,你试图将这个对象塞到一个只接受 Profile 对象的 List<Profile> 中。因此,它抱怨你试图将这个匿名对象放到只能接受 Profile 对象的List中。

既然你在匿名类型中使用的字段与Profile类型中的字段相同,为什么不用 new Profile { ... 替换 new { ... 呢?

最后,也要去掉末尾的 ToListCast


1
请问如何将匿名对象放入上述示例中的List中? - user995099
除非使用像ArrayList这样的弱类型列表,否则无法实现。请参阅我的编辑以了解如何修复您的代码,以便您可以像现在一样使用强类型列表。 - Øyvind Bråthen
哇!你救了我半天的苦恼。问题出在匿名对象上。 - Florida G.

4
那是因为匿名类型 <>f__AnonymousType1'2 [System.Int64,System.String] 不是 Profile!(既不是实例也不是祖先的实例)。尝试像这样替换您的选择:
select new CustomerConfidentialProfile
{
CustomerProfileId = c.CustomerProfileId,
FirstName = c.FirstName,
AddressLine1 = a.Line1,
property assignments go futher   
})

哈哈,我谷歌了好久,最终找到了这个线索,让我知道该怎么做。我在LINQ中连接了两个表,只想要第二个表的一列..我想到应该创建一个包含我所需列的类,但是在控制器中无法加载它,并在视图中使用foreach,直到我读到这篇文章并为我的新类中的列做了完全相同的事情。得到了我的支持。我喜欢StackOverFlow。 - JustJohn

1
你不能将匿名类型转换为命名类型。但是你可以直接构造一个命名类型:
select new CustomerConfidentialProfile()
                   {
                       CustomerProfileId = c.CustomerProfileId,
                       FirstName = c.FirstName
               AddressLine1 = a.Line1   
                   }).ToList();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接