所以我是linq的新手,所以请注意我正在做的事情可能完全是愚蠢的!

我有一个casestudies表和一个服务表,其中包含多对多的关系

案例研究已经存在,我正在尝试插入服务,同时将已经存在的一些案例研究联系起来。我假设这样的东西会起作用吗?

 Service service = new Service()
        {
            CreateDate = DateTime.Now,
            CreatedBy = (from u in db.Users
                         where u.Id == userId
                         select u).Take(1).First(),
            Description = description,
            Title = title,
            CaseStudies = (from c in db.CaseStudies
                           where c.Name == caseStudy
                           select c),
            Icon = iconFile,
            FeatureImageGroupId = imgGroupId,
            UpdateDate = DateTime.Now,
            UpdatedBy = (from u in db.Users
                         where u.Id == userId
                         select u).Take(1).First()

        };

但这不正确,因为它抱怨

无法将类型'System.Linq.IQueryable'隐式转换为'System.Data.Objects.DataClasses.EntityCollection'

有人可以告诉我正确的方法。

提前致谢

有帮助吗?

解决方案

哟必须将查询结果添加到案例研究集合中,而不是尝试替换它。

var service = new Service { ... };                     

foreach (var caseStudy in db.CaseStudies.Where(s => s.Name == caseStudyName)
{
    service.CaseStudies.Add(caseStudy);
}

您可以将它包装在扩展方法中并获得一个很好的语法。

public static class ExtensionMethods
{
    public static void AddRange<T>(this EntityCollection<T> entityCollection,
                                        IEnumerable<T> entities)
    {
        // Add sanity checks here.
        foreach (T entity in entities)
        {
            entityCollection.Add(entity);
        }
    }
}

现在你得到以下内容。

var service = new Service { ... };                     

service.CaseStudies.AddRange(db.CaseStudies.Where(s => s.Name == caseStudyName));
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top