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

use*_*099 3 c# linq-to-entities

我对Linq和实体框架工作很新,我的下面的代码有问题.我收到了错误

无法转换类型的对象<> 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; }
        }
}
Run Code Online (Sandbox Code Playgroud)

任何帮助将不胜感激.

Øyv*_*hen 8

您的问题是从LINQ查询返回一个匿名类型(通过使用new { ... }语法.

但是,您尝试将此对象阻塞到List<Profile>.所以它抱怨你试图将这个匿名对象放入只接受Profile对象的List中.

为什么不替换new { ...,new Profile { ...因为您在匿名类型中使用与在配置文件类型中相同的字段.

并删除ToList,Cast最后也是.