Reputation: 2596
I am trying to create some entities using linq, and must be doing something wrong
var ptemp = repository.PackageTemplates.Where(f => f.employeeId == data.EmployeeId).SingleOrDefault();
File file = AddFileStreams(StrToByteArray(data.FileDataIn), data.FileNameForDevice, repository, packageTypeItemId);
// add new packageItemTemplate
var pit = AddPackageItemTemplate((PackageTemplate)ptemp, file, repository, EnumPackageItemTemplatesCommand.DownloadFile, 0);
// Adds package Item for each package
repository.Packages.Where(pi => pi.PackageTemplate == ptemp).ToList().ForEach(pk =>
{
AddPackageItem(pit, pk, repository);
});
The error is in passing the type of Packages
to another function as part of a LINQ ForEach()
the type of pit
has no problems, do I need to create a list first and loop througn it after? I cant seemt o find an explanation.
The error message I recieve is:
Unable to create a constant value of type 'PackageTemplate'.
Only primitive types ('such as Int32, String, and Guid') are supported
in this context.
If I change to:
// Adds package Item for each package
repository.Packages.Where(pi => pi.PackageTemplateId == ptemp.Id).Select(pk => pk).ToList().ForEach(pk =>
{
AddPackageItem(pit, pk, repository);
});
and use the ID in the where clause rather than the navigation property then it works, does anyone know what the issue is?
Upvotes: 0
Views: 57
Reputation: 4960
Unfortunately that's just the way it works.
Note that what does it evaluates the expression tree and converts it to SQL statements or whatever data source you are using. Since it cannot compare entire objects in the same way it can in managed code, it also does no guessing as to whether the two entities are really equal just based on their keys (which are not even always defined).
On the other side, comparing two primitive values is what it can always do.
Upvotes: 2