Suppose I have an automatically-generated Employee
class based on the Employees
table in my database.
Now suppose that I want to pass employee data to a ShowAges
method that will print out name & age for a list of employees. I'll retrieve the data for a given set of employees via a linq query, which will return me a set of Employee
instances. I can then pass the Employee
instances to the ShowAges
method, which can access the Name
& Age
fields to get the data it needs.
However, because my Employees
table has relationships with various other tables in my database, my Employee
class also has a Department
field, a Manager
field, etc. that provide access to related records in those other tables. If the ShowAges
method were to invok开发者_运维问答e any of those methods, this would cause lots more data to be fetched from the database, on-demand.
I want to be sure that the ShowAges
method only uses the data I have already fetched for it, but I really don't want to have to go to the trouble of defining a new class which replicates the Employee
class but has fewer methods. (In my real-world scenario, the class would have to be considerably more complex than the Employee
class described here; it would have several 'joined' classes that do need to be populated, and others that don't).
Is there a way to 'switch off' or 'disconnect' the Employees
instances so that an attempt to access any property or related object that's not already populated will raise an exception?
If not, then I assume that since this must be a common requirement, there might be an already-established pattern for doing this sort of thing?
maybe not the answer you're looking for,but how about projecting the results of your query into a more light-weight POCO, eg:
var employeePOCOs = from e in l2sEmployees
select new EmployeePOCO
{
Id = e.Id,
Name = e.FirstName + " " + e.LastName
};
where EmployeePOCO is a predefined class
would that help? I've used this when returning Entity Framework objects back through an AJAX call where the output was going to JSON, and it seemed to do the trick.
One way to do this is to 'detach' the entity from its database context. Take a look at an answer I gave to a similar question. It shows you a couple ways of detaching entities.
精彩评论