Setting a collection of related entities in the correct way in EF4 using POCO's (src is the DB)
I have a POCO entity Report
with a collection of a related POCO entity Reference
. When creating a Report
I get an ICollection<int>
of ids. I use this collection to query the reference repository to get an ICollection<Reference>
like so:
from r in referencesRepository.References
where viewModel.ReferenceIds.Contains(r.Id)
select r
I would like to connect the collection straight to Report
like so:
report.References = from r in referencesRepository.References
where viewModel.ReferenceIds.Contains(r.Id)
select r;
This doesn't work because References
is an ICollection
and the result is an IEnumerable
. I can do ToList()
, but I think I will then load all of the references into memory. There also is no AddRange()
function.
I would like to be able to do this without loading them into memory.
My question is very similar to this one. There, the only solution was to loop through the items and add them one by one. Except in this question the list of references 开发者_Go百科does not come from the database (which seemed to matter). In my case, the collection does come from the database. So I hope that it is somehow possible.
Thanks in advance.
When working with entity framework you must load objects into memory if you want to work with them so basically you can do something like this:
report.References = (from r in referencesRepository.References
where viewModel.ReferenceIds.Contains(r.Id)
select r).ToList();
Other approach is using dummy objects but it can cause other problems. Dummy object is new instance of Reference
object which have only Id set to PK of existing object in DB - it will act like that existing object. The problem is that when you add Report
object to context you must manually set each instance of Reference
in ObjectStateManager
to Unchanged
state otherwise it will insert it to DB.
report.References = viewModel.ReferenceIds.Select(i => new Reference { Id = i }).ToList();
// later in Report repository
context.Reports.AddObject(report);
foreach (var reference in report.References)
{
context.ObjectStateManager.ChangeObjectState(reference, EntityState.Unchanged);
}
精彩评论