Entity Framework - Where Clause - asp.net

Let's say i have a table named User.
When I use the Entity Framework to get the records i do like this:
var db = new Context();
var users = db.Users;
It return all the users in my table. OK. If i do this:
var fooUsers = db.Users.Where(u => u.Name == 'foo');
It will give me all the users with name 'foo'. OK. My question is:
The entity framework make a query like:
select * from user where name = 'foo'
Or it load all the users and filter them on the server with lambda expression?

The Sql submitted to your database will contain your where clause. You can use SQL Server Profiler to watch as queries are submitted to your DB.

Entity Framework will translate such a query into a "Store Expression." That is, it will generate a database query -- assuming your data storage is a database -- that will be somewhat similar to the query you included in your question. It very well may name the columns, however, and there are likely to be some other differences.

From here http://msdn.microsoft.com/en-us/library/cc853327.aspx
When you create an ObjectQuery or LINQ query, the query may not be executed immediately. Query execution is deferred until the results are needed, such as during a foreach (C#) or For Each (Visual Basic) enumeration or when it is assigned to fill a List collection. Query execution begins immediately when you call the Execute method on an ObjectQuery or when you call a LINQ method that returns a singleton query, such as First or Any. For more information, see Object Queries and Query Execution (LINQ to Entities).
So when your query has a WHERE clause it will just load the results filtered by the database with the where.

Related

How to retrieve an entity using a property from datastore

Is it possible to retrieve an entity from gae datastore using a property and not using the key?
I could see I can retrieve entities with key using the below syntax.
quote = mgr.getObjectById(Students.class, id);
Is there an alternative that enables us to use a property instead of key?
Or please suggest any other ways to achieve the requirement.
Thanks,
Karthick.
Of course this is possible. Think of the key of an entity being like the primary key of an SQL row (but please, don't stretch the analogy too far - the point is it's a primary key - the implementations of these two data storage systems are very different and it causes people trouble when they don't keep this in mind).
You should look either here (JDO) to read about JDO queries or here (JPA) to read about JPA queries, depending what kind of mgr your post refers to. For JDO, you would do something like this:
// begin building a new query on the Cat-kind entities (given a properly annotated
// entity model class "Cat" somewhere in your code)
Query q = pm.newQuery(Cat.class);
// set filter on species property to == param
q.setFilter("species == speciesParam");
// set ordering for query results by age property descending
q.setOrdering("age desc");
// declare the parameters for this query (format is "<Type> <name>")
// as referenced above in filter statement
q.declareParameters("String speciesParam");
// run the query
List<Cat> results = (List<Cat>) q.execute ("siamese");
For JPA, you would use JPQL strings to run your queries.

Entity Framework 5, Code First, Full Text Search but IQueryable via CreateQuery?

I am using .NET 4.5 and EF 5 with Code First approach and now I need to implement Full Text Search.
I have already read a lot about it and so far my conclusions are:
Stored procedures nor Table Value Functions can not be mapped with Code First.
Still I can call them using dynamic sql
dbContext.Database.SqlQuery<Movie>(Sql, parameters)
But this returns IEnumerable and I want IQueryable so that I can do more filtering before fetching the data from db server. I know I can send those parameters to Db function but I don't want that.
What I have found that could fulfill my needs is CreateQuery function from IObjectContextAdapter that looks like this(Select All just for test):
IQueryable<Movie> result = ((IObjectContextAdapter)dbContext).ObjectContext.CreateQuery<Movie>("SELECT * FROM Movie");
However executing this throws Exception"
'System.Data.EntitySqlException was unhandled
HResult=-2146232006
Message=The query syntax is not valid. Near term '*', line 1, column 9.'
So the questions are:
Why do I get this exception and can it be fixed ?
If not is there any way with Code First to do FTS that returns IQueryable ?
Try it like this
ObjectQuery<Movie> query =
objectContext.CreateQuery<Movie>(#"SELECT VALUE movie FROM Movies");
As for why see these links
Differences from Transact-SQL Unlike Transact-SQL, Entity SQL does not
support use of the * argument in the SELECT clause. Instead
Entity SQL Reference - SELECT
"SELECT VALUE" - value keyword in LINQ/Entity Framework query

Can I execute a scalar query in EF 4.1?

Is it possible to execute a scalar-valued query using EF 4.1?
I've tried:
ObjectQuery<int> query = new ObjectQuery<int>("select count(*) from myTable", _context);
var result = query.Execute(MergeOption.NoTracking);
return result.FirstOrDefault();
but it returns an error: The query syntax is not valid. Near term '*'
Is the only way to execute a scalar-valued query to call a stored proc?
It seems to me that you are thinking of entity framework as an "ADO.net 2.0" rather than the ORM that it is.
Rather than using it to execute SQL queries, I'd recommend using the standard entity framework Data container and using a LINQ query, as is intended with entity framework. Then it would simply be something like
myDataContainerInstance.myTable.Count()
ObjectQuery isn't analogous to the ADO.net command and doesn't execute SQL statements. Instead it is used to define queries against the object model directly. The (*) isn't valid because it isn't SQL.

View with Not exists join to be used in Entity Framework

I need to create a view in SQL Server and to use it in a GridView on my .aspx page.
The view is mapped in my application through Entity Framework.
Here's my example:
SELECT User.UserName, User.UserId
FROM User
WHERE NOT EXISTS (SELECT UsersInRoles.RoleId FROM UsersInRoles
WHERE UsersInRoles.UserId = User.UserId AND UsersInRoles.RoleId = 'AdminRole')
The relation between User and UsersInRoles table is one-to-many.
I need to be able to pass the AdminRole value in my ASP.NET application.
I cannot use parameters in a view (i.e. using #Role is not allowed).
Only views and tables can bind to a GridView so a stored procedure (where a parameter
could be an option) is not good here.
Is there a workaround to use a LEFT OUTER JOIN maybe instead of the NOT EXISTS?
This way, having a JOIN on the UsersInRoles table, I could map the fields from UsersInRoles through Entity Framework in my application and I could add conditions there (with EntityDataSource.Where clause).
For Exists, use the Any extension method in LINQ. For Not Exists, use !Any.
var query = from user in User
where !user.UsersInRoles.Any(role => role.RoleId == 'AdminRole')
select new {user.UserName, user.UserId};
I'm quite new in EF, but I know that we can use stored procedures (or functions) in it.
Try read this

For repetitive "SELECT" query, does Linq access databsase each time or it gives you values from its in-memory Entity objects?

By Linq, I mean Entity Framework and Linq. A further question, if the SELECT query is the same, but OEDER BY clause is different, does Linq have to access the database or the in-memory entities have enough information for the new SELECT query with different ORDER BY clause?
The short answer is no, once the Entity is created, the Entity itself contains all the information that will be used for data binding, unless you explicitly instruct the Entity to requery the underlying data store.

Resources