简体   繁体   中英

How can I use LINQ to populate a collection inside a class?

I have the following:

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

The problem with this is that it gives me an error in the VS2012 IDE on the select. Here it says:

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?

Here is the Application class:

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

Use 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()
    });
 }

You need a cast to IList<TestAccount> .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM