How do you execute custom SQL in EF CTP4
Using Entity Framework CPT4 is there a way to execute a custom command or script?
for example:
_dbSet.Provider.Execute("Truncate Table Users");
FWIW; I will be using this in the class setup for my unit tests and will setup the ta开发者_开发百科bles with clean data.
Try the ObjectContext.ExecuteStoreCommand
method.
Executes an arbitrary command directly against the data source using the existing connection.
Calling the ExecuteStoreCommand method is equivalent to calling the ExecuteNonQuery method of the DbCommand class.
Some other good information: Tip 41 – How to execute T-SQL directly against the database
With this example for ExecuteStoreCommand
:
// 10% inflation day!
ctx.ExecuteStoreCommand("UPDATE Products SET Price = Price * 1.1");
The quickest workaround I can think of is the use of stored procs. An alternative is to use batch delete described http://www.aneyfamily.com/terryandann/post/2008/04/Batch-Updates-and-Deletes-with-LINQ-to-SQL.aspx <-- here, but the code is based on Linq2Sql, not EF, you will have to port it.
Maybe take a look at ndbunit to setup and teardown your database for unit tests
Edit:
This is what we are using on our application for unit/integration testing our data access layer which is actually implemented using EF4. It's fairly straightforward and provides a nice way to inject and cleanup repeatable test data.
However, we also have the need to delete/truncate a table in the application logic itself using EF. So to answer your original question, we've just incorporate the "delete from table" script in a stored proc which we then call from EF using
_dataContext.ExecuteFunction("SchemaName.MyTableDeleteProc");
精彩评论