How to Delete Multiple Records in the Entity Framework Without Looping

The Microsoft ADO.NET Entity Framework provides developers with the tools necessary to easily interact with databases. The Entity Framework adds a level of abstraction between databases and the programs that interact with them, which simplifies many standard database actions a programmer might want to implement. For example, you can remove multiple records in a database without using a loop that tests every record. This can be accomplished using the ADO.NET "ADOCommand" method, which sends a command to a database.

Instructions

    • 1

      Click the Visual Studio 2010 icon to launch the software. After it loads, the "Home Page" is displayed. Click on the button labeled "New Project" in the upper-right corner of this page. A "New Project" window opens.

    • 2

      Click "C#" from the column on the left and "Console Application" from the column on the right. Press the "OK" button to create a new project. A source code file appears in the main editor window.

    • 3

      Add the following lines to the top of the source code file. These lines ensure that ADO.NET functions are available for your program to use.

      using System.Data;

      using System.Data.ADO;

      using System.Globalization;

    • 4

      Locate the "main" method, which was automatically generated when you created the project. All of the source code from the following steps must be written inside the curly brackets of the "main" method. The method looks like this:

      static void Main(string[] args)

      {

      }

    • 5

      Create a connection string to the database you want to delete records from. Connection strings are highly specific to the individual database. Your connection string might look something like this:

      public const string connectionString =

      " Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;";

    • 6

      Create a string that stores the "Delete" command. The following example deletes all "Account" records that have an "Expired" field set to "True."

      String deleteExpiredAccounts = "DELETE FROM Account WHERE Expired = 'True'";

    • 7

      Create a new "ADOCommand" that uses the strings "deleteExpiredAccounts" and "connectionString." Once a connection to the database is opened, this command deletes all the accounts that have expired:

      ADOCommand cmd = new ADOCommand( deleteExpiredAccounts, connectionString);

    • 8

      Open the connection to the database by using the "Open" command, like this:

      cmd.ActiveConnection.Open();

    • 9

      Click the green "Play" button to execute the program, which is located at the top of the Visual Studio program window. The program will connect to the database and delete all expired accounts without using any looping logic.

Related Searches:

References

Resources

Comments

Related Ads

Featured