简体   繁体   中英

execute custom sql with entity framework4

i have to receive workorders from the database, specific for the user.

The filter for all users is different, so one must do all order shipped to UK, ont all to 5 other countries, one does all the high value things, one does al the order which containt > 10 items etc.

So, what i came up with this idea (shoot at it if you have a better one!)

i create a view for each user, and all the views return the same data, but the filter is different.

In ado.net i would do something like this:

string sql = "select * from vwWorkOrders" + userName;
[rest of the ado.net here]

but now i'm using ef4, and i was wondering what is the equivalent of this kind of code.

You can use the ExecuteStoreQuery method like in the following example:

context.ExecuteStoreQuery<vwWorkOrder>(sql);

This method allows you to execute storage SQL and obtain strongly-typed results.
In case you need to pass some parameters, just pass necessary ObjectParameter instances in the call of ExecuteStoreQuery.

You can use eSQL, which allows for a little more flexibility in your queries. You might download LinqPad to play around with it beforehand.

// whereClause is a string
string query = string.Format("select * from ObjectContext.vwWorkOrders where {0}", whereClause);

Then just use the EntityConnection and EntityCommand classes to execute your command and loop over the results in a manner not altogether different from ADO.NET.

EDIT: I just saw your comment; I thought that you had a typo in your example. A more suitable code snippet for what you are trying to achieve:

// userName is a string, ie "Michel"
string query = string.Format("select * from ObjectContext.vwWorkOrders{0}", userName);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM