I’m trying to set an EntityCollection property (v.TPM_USER2) to a subset of users in my database. I have the array view.DNs which contains a list of usernames to add. I can do this with:
if(view.DNs != null && view.DNs.Length > 0)
{
var users = (from u in context.TPM_USER where view.DNs.Contains(u.DN) select u);
foreach (var u in users)
{
v.TPM_USER2.Add(u);
}
}
This works fine, however I have a feeling there’s a way to do this with a single line of code. I’ve tried:
v.TPM_USER2 = (from u in context.TPM_USER where view.DNs.Contains(u.DN) select u);
Which results in the error:
Error 78 Cannot implicitly convert type
‘System.Linq.IQueryable’ to
‘System.Data.Objects.DataClasses.EntityCollection
I’ve tried using ToArray() as well without any luck. Is there a way to do this?
UPDATE:
I also tried:
v.TPM_USER2.Attach(from u in context.TPM_USER where view.DNs.Contains(u.DN) select u);
Which compiles, but generates the runtime error:
Attach is not a valid operation when the source object associated with
this related end is in an added, deleted, or detached state. Objects
loaded using the NoTracking merge option are always detached.
v.TPM_User2.AddRange(users);Edit: That was for
EntitySet– looks like you may be stuck with foreach. Alternatively, you could write your ownAddRangeextension method to do the looping for you if you’re dedicated to doing it one line.