3

How to execute sql statement in asp.net mvc3 (C#)? I am using Entity Data Model for my asp.net mvc application

I need to execute a sql query ("select * from users where EmailAddress like '%@gmail.com'").

4
  • Look into NHibernate or DAL Wrappers. Commented Jun 9, 2011 at 10:48
  • 1
    Use an SqlConnection to execute the SqlCommand. Ideally this should be done in the Model, which in turn is called by an action in the Controller. Commented Jun 9, 2011 at 10:49
  • do you not have a User Entity? Commented Jun 9, 2011 at 11:19
  • Yes I have that entity, but i need this to achieve a particular scenario where the admin can filter the users based on custom query(like advanced search). When the admin uses advanced search, i can construct a query and trying to execute and get the results Commented Jun 9, 2011 at 11:21

1 Answer 1

5

Is your User entity mapped? In such case yo can use

var users = from u in context.Users
            where u.EmailAddress.EndsWith("@gmail.com")
            select u;

If you don't have User table mapped but you have User class with parameterless constructor and public settable properties with same names as columns in result set you can use:

var users = context.ExecuteStoreQuery<User>("select * from users where EmailAddress like '%@gmail.com'");

in case of ObjectContext API or:

var users = context.Database.SqlQuery<User>("select * from users where EmailAddress like '%@gmail.com'");

If you don't have entity you can execute it as any other ADO.NET command by creating SqlConnection, SqlCommand and calling ExecuteReader on the command.

Sign up to request clarification or add additional context in comments.

3 Comments

Can we join multiple tables with ExecuteStoreQuery?
You can excute any SQL query with that method, so you can join tables as well.
Can you execute a query this way on multiple tables?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.