CRUD operation in .net 7 using ADO.NET



CRUD operations (Create, Read, Update, Delete) are the basic database operations that are used to manage data in a database. In .NET 7, you can perform CRUD operations using various methods and technologies, such as ADO.NET, Entity Framework, or LINQ.


Here is an example of how you can perform CRUD operations using ADO.NET in .NET 7:


using (SqlConnection connection =
     new SqlConnection(connectionString))
{
    connection.Open();

    // Create
    string insertSql = "INSERT INTO Customers
    (Name, Email) VALUES (@Name, @Email)";
    using (SqlCommand insertCommand =
    new SqlCommand(insertSql, connection))
    {
        insertCommand.Parameters
            .AddWithValue("@Name", "John Smith");
        insertCommand.Parameters
            .AddWithValue("@Email", "john@example.com");
        insertCommand.ExecuteNonQuery();
    }

    // Read
    string selectSql =
    "SELECT * FROM Customers WHERE Email = @Email";
    using (SqlCommand selectCommand =
    new SqlCommand(selectSql, connection))
    {
        selectCommand.Parameters
            .AddWithValue("@Email", "john@example.com");
        using (SqlDataReader reader =
        selectCommand.ExecuteReader())
        {
            while (reader.Read())
            {
            Console
            .WriteLine("{0} {1}",reader["Name"], reader["Email"]);
            }
        }
    }

    // Update
    string updateSql =
        "UPDATE Customers SET Name =
        @Name WHERE Email = @Email";
    using (SqlCommand updateCommand =
        new SqlCommand(updateSql, connection))
    {
        updateCommand.Parameters
            .AddWithValue("@Name", "John Doe");
        updateCommand.Parameters
            .AddWithValue("@Email", "john@example.com");
        updateCommand.ExecuteNonQuery();
    }

    // Delete
    string deleteSql =
    "DELETE FROM Customers WHERE Email = @Email";
    using (SqlCommand deleteCommand =
    new SqlCommand(deleteSql, connection))
    {
        deleteCommand.Parameters
            .AddWithValue("@Email", "john@example.com");
        deleteCommand.ExecuteNonQuery();
    }
}

This example uses ADO.NET to connect to a SQL Server database, execute a series of SQL statements, and perform CRUD operations on a Customers table. The SqlConnection, SqlCommand, and SqlDataReader classes are part of the ADO.NET API and are used to manage the connection to the database, execute SQL statements, and read query results.


You can also use the Entity Framework or LINQ to perform CRUD operations in .NET 7. These technologies provide a higher-level API that abstracts the details of database access and allows you to work with data in a more object-oriented way.


Reactions

Post a Comment

0 Comments