views:

47

answers:

1

Is it possible to pass a SQL script to some method that Entity Framework has to run it against my model? e.g. equivalent of:

context.ExecuteStoreCommand(<tsql script path>); 

Background: I want a way to reset the database during unit tests, and making a call to run the EF generated TSQL script (from Generate Database from Model) seems one way to achieve this.

A: 

You can get the underlying DbConnection object and use it to generate DbCommand and execute the SQL statement.

Or you can do it like this (taken from MSDN)

using (AdventureWorksEntities context =
    new AdventureWorksEntities())
{
    // Create a query that takes two parameters.
    string queryString =
        @"SELECT VALUE Contact FROM AdventureWorksEntities.Contacts 
                AS Contact WHERE Contact.LastName = @ln AND
                Contact.FirstName = @fn";

    ObjectQuery<Contact> contactQuery =
        new ObjectQuery<Contact>(queryString, context);

    // Add parameters to the collection.
    contactQuery.Parameters.Add(new ObjectParameter("ln", "Adams"));
    contactQuery.Parameters.Add(new ObjectParameter("fn", "Frances"));

    // Iterate through the collection of Contact items.
    foreach (Contact result in contactQuery)
        Console.WriteLine("Last Name: {0}; First Name: {1}",
        result.LastName, result.FirstName);
}
Itay
-1: He's talking about T-SQL, not Entity SQL.
John Saunders
John - that is why I opened my answer with "You can get the underlying DbConnection object and use it to generate DbCommand and execute the SQL statement."
Itay
Your example is ESQL, not T-SQL, though.
Craig Stuntz