如何使用LINQ填充类中的集合?
本文关键字:集合 何使用 LINQ 填充 | 更新日期: 2023-09-27 18:05:40
我有以下内容:
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; }
}
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()
});
}
您需要转换到IList<TestAccount>
。
{
Name = applicationName,
ModifiedDate = DateTime.Now,
TestAccounts = (from testAccountName in testAccountNames
select new TestAccount
{
Name = testAccountName ,
ModifiedDate = DateTime.Now
}).ToList() // <-- try this
});