I would like to add a new entity to a database having used EF to retrieve other instances of the data. I was hoping to use code such as below:
using (var db = new FundResearchContext(null))
{
var query = from a in db.As select new
{
a = a,
bs = (from b in db.Bs where b.AnId == a.AnotherId select b)
};
var listOfAsAndRelatedBs = query.ToList();
listOfAsAndRelatedBs[0].bs.Add(new B());
db.SaveChanges();
}
Whilst the objects in the bs collection are tracked and changes to them are saved, I can’t add new items to the collection because it is of type IQueryable. I realise that in a simple case like this I could put properties on A an B to indicate they are linked via a Foreign Key, but that approach is not posssible in my real life scenario. So is there an alternative syntax that would make bs itself a tracked object to which I could add new B objects and have them persisted? Or do I have to do it all manually using db.Bs.Add(new B())?
If your
Aclass has aBscollection on it, you can say:This has a nice eager-loading effect, since all of the
Bs for eachAare loaded in and attached when this query is materialized. And you should be able to add objects to either thebsproperty or thea.Bsproperty of one of the results.If you don’t have this relationship set up between your Entity classes, you’re not going to be able to do this, and you’ll be stuck adding to
db.Bsdirectly. Of course, you can create a sort of shortcut object to facilitate this:That way you don’t have to have access to the context directly to add an item to the
Bs.