如何使用LINQ填充类中的集合?

时间:2013-03-25 20:21:25

标签: c# linq

我有以下内容:

     foreach (string applicationName in applicationNames)
     {
     _uow.Applications.Add(
        new Application 
        { 
            Name = applicationName, 
            ModifiedDate = DateTime.Now,
            TestAccounts = (from  testAccountName in testAccountNames
                            select new TestAccount
                            { 
                               Name = testAccountName , 
                               ModifiedDate = DateTime.Now 
                           })
        });
     }

这个问题是它在选择的VS2012 IDE中给出了一个错误。这里说:

Error   3   Cannot implicitly convert type 
'System.Collections.Generic.IEnumerable<Relational.Models.TestAccount>' to
'System.Collections.Generic.ICollection<Relational.Models.TestAccount>'.
An explicit conversion exists (are you missing a cast?

这是Application类:

public partial class Application
{
    public Application()
    {
        this.TestAccounts = new List<TestAccount>();
    }

    public int ApplicationId { get; set; }
    public string Name { get; set; }
    public virtual byte[] Version { get; set; }
    public System.DateTime ModifiedDate { get; set; }
    public virtual ICollection<TestAccount> TestAccounts { get; set; }
}

2 个答案:

答案 0 :(得分:5)

使用ToList

 foreach (string applicationName in applicationNames)
 {
 _uow.Applications.Add(
    new Application 
    { 
        Name = applicationName, 
        ModifiedDate = DateTime.Now,
        TestAccounts = (from  testAccountName in testAccountNames
                        select new TestAccount
                        { 
                           Name = testAccountName , 
                           ModifiedDate = DateTime.Now 
                       }).ToList()
    });
 }

答案 1 :(得分:1)

您需要转换为IList<TestAccount>

    { 
        Name = applicationName, 
        ModifiedDate = DateTime.Now,
        TestAccounts = (from  testAccountName in testAccountNames
                        select new TestAccount
                        { 
                           Name = testAccountName , 
                           ModifiedDate = DateTime.Now 
                       }).ToList()     // <-- try this
    });