I'd recommend not using AddWithValue, see the following.
A guideline to follow.
- Use a class/model, pass it to a dedicate method for an add record
- Have some form of exception handling in the event bad things happen e.g. server down etc
- For connection and command objects implement with
using declarations
or using statements
.
- Return a named value tuple, success and an exception object or in your what suits your needs.
- Consider using Entity Framework Core, so much easier for web (Blazor, Razor etc)
Sample code done with C# 10/11 and note there are two quires, the insert and one to get the new key.
using System.ComponentModel.DataAnnotations;
using System.Data;
using Microsoft.Data.SqlClient;
namespace SqlServerLibrary;
public class DataOperations
{
private static readonly string ConnectionString =
"TODO";
public static (bool success, Exception exception) AddCustomer(Customer customer)
{
using var cn = new SqlConnection(ConnectionString);
using var cmd = new SqlCommand
{
Connection = cn,
CommandText =
@"
INSERT INTO dbo.Customer (CompanyName, ContactName, ContactTypeIdentifier, GenderIdentifier)
VALUES (@CompanyName, @ContactName, @ContactTypeIdentifier, @GenderIdentifier);
SELECT CAST(scope_identity() AS int);"
};
cmd.Parameters.Add("@CompanyName", SqlDbType.NChar).Value =
customer.CompanyName;
cmd.Parameters.Add("@ContactName", SqlDbType.NChar).Value =
customer.ContactName;
cmd.Parameters.Add("@ContactTypeIdentifier", SqlDbType.Int).Value =
customer.ContactTypeIdentifier;
cmd.Parameters.Add("@GenderIdentifier", SqlDbType.Int).Value =
customer.GenderIdentifier;
try
{
cn.Open();
customer.Identifier = Convert.ToInt32(cmd.ExecuteScalar());
return (true, null);
}
catch (Exception localException)
{
return (false, localException);
}
}
}
public class Customer
{
public int Identifier { get; set; }
[Required]
public string CompanyName { get; set; }
[Required]
public string ContactName { get; set; }
[Required]
public int? ContactTypeIdentifier { get; set; }
[Required]
public int? GenderIdentifier { get; set; }
public override string ToString() => CompanyName;
}
Then a sample call not fully done in regards to setting the Customer properties
Customer customer = new ();
var (success, exception) = DataOperations.AddCustomer(customer);
if (success)
{
// the customer object has a assigned primary key
}
else if (exception is not null)
{
// does something with the exception e.g. log it, tell user...
}