I have the following method automatically generated from the scaffold template with repository:-
public Group Find(int id) { return context.Groups.Find(id); }
But since the Groups object has two navigation properties which I need , so I wanted to include the .Include
, so I replace the .find
with .where
:-
public Group Find(int id) { return context.Groups.Where(c=>c.GroupID==id) .Include(a => a.UserGroups) .Include(a2 => a2.SecurityRoles) .SingleOrDefault(); }
But my question is how can I apply the .Include
with the .find()
instead of using .Where()
?
JavaScript Array find() The find() method returns the value of the first element that passes a test. The find() method executes a function for each array element. The find() method returns undefined if no elements are found.
The find command is used to search and locate the list of files and directories based on conditions you specify for files that match the arguments. find command can be used in a variety of conditions like you can find files by permissions, users, groups, file types, date, size, and other possible criteria.
I was just thinking about what find actually does. @lazyberezovsky is right include and find cant be used in conjunction with each other. I think this is quite deliberate and here's why:
The Find method on DbSet uses the primary key value to attempt to find an entity tracked by the context. If the entity is not found in the context then a query will be sent to the database to find the entity there. Null is returned if the entity is not found in the context or in the database.
Find is different from using a query in two significant ways:
- A round-trip to the database will only be made if the entity with the given key is not found in the context.
- Find will return entities that are in the Added state. That is, Find will return entities that have been added to the context but have not yet been saved to the database.
(from http://msdn.microsoft.com/en-us/data/jj573936.aspx)
Because find is an optimised method it can avoid needing a trip to the server. This is great if you have the entity already tracked, as EF can return it faster.
However if its not just this entity which we are after (eg we want to include some extra data) there is no way of knowing if this data has already been loaded from the server. While EF could probably make this optimisation in conjunction with a join it would be prone to errors as it is making assumptions about the database state.
I imagine that include and find not being able to be used together is a very deliberate decision to ensure data integrity and unnecessary complexity. It is far cleaner and simpler when you are wanting to do a join to always go to the database to perform that join.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With