在ASP.NET中使用三层架构(Presentation Layer, Business Logic Layer, Data Access Layer)来确保数据一致性是非常重要的。以下是一些关键步骤和最佳实践:
using (var transaction = connection.BeginTransaction())
{
try
{
// 执行数据库操作
dataAccessLayer.Insert(entity);
dataAccessLayer.Update(anotherEntity);
dataAccessLayer.Delete(yetAnotherEntity);
transaction.Commit();
}
catch (Exception ex)
{
transaction.Rollback();
throw;
}
}
var command = new SqlCommand("sp_InsertUser", connection);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.AddWithValue("@Username", username);
command.Parameters.AddWithValue("@Email", email);
connection.Open();
command.ExecuteNonQuery();
connection.Close();
using (var context = new ApplicationDbContext())
{
context.Database.BeginTransaction();
try
{
var user = new User { Username = username, Email = email };
context.Users.Add(user);
context.SaveChanges();
var profile = new Profile { UserId = user.Id, Bio = bio };
context.Profiles.Add(profile);
context.SaveChanges();
context.Database.CommitTransaction();
}
catch (Exception ex)
{
context.Database.RollbackTransaction();
throw;
}
}
if (string.IsNullOrEmpty(username) || !email.IsValidEmail())
{
throw new ArgumentException("Invalid input");
}
public class UserDTO
{
public int Id { get; set; }
public string Username { get; set; }
public string Email { get; set; }
}
services.AddScoped<IUserRepository, UserRepository>();
services.AddScoped<IUserProfileRepository, UserProfileRepository>();
通过遵循这些最佳实践,可以有效地确保ASP.NET三层架构中的数据一致性。