views:

265

answers:

1

So I'm new to linq so be warned what I'm doing may be completely stupid!

I've got a table of caseStudies and a table of Services with a many to many relasionship

the case studies already exist and I'm trying to insert a service whilst linking some case studies that already exist to it. I was presuming something like this would work?

 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()

        };

But This isn't correct as it complains about

Cannot implicitly convert type 'System.Linq.IQueryable' to 'System.Data.Objects.DataClasses.EntityCollection'

Can somebody please show me the correct way.

Thanks in advance

A: 

Yo have to add the query result to the case studies collection instead of trying to replace it.

var service = new Service { ... };                     

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

You can wrap this in an extension method and get a nice syntax.

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

And now you get the following.

var service = new Service { ... };                     

service.CaseStudies.AddRange(db.CaseStudies.Where(s => s.Name == caseStudyName));
Daniel Brückner
thats what I feared :S doesn't seem the best way of doing it to me
mjmcloug
You can of course write an extension method AddRange taking an EntityCollection<T> and an IEnumerable<T> that adds all the items at once.
Daniel Brückner
By the way ... if your way from the question would work, you would always lose all the entities already in the collection when you assign a new collection - certainly not something you want to do in most cases.
Daniel Brückner