using (var connection = new SqlConnection(connectionString))
{
}
- 使用ConfigurationManager或环境变量存储
- 避免硬编码
- 考虑使用Azure Key Vault等安全存储方案
var cmd = new SqlCommand(
"SELECT * FROM Users WHERE Username = @username",
connection);
cmd.Parameters.AddWithValue("@username", inputUsername);
var cmd = new SqlCommand("sp_GetUserDetails", connection)
{
CommandType = CommandType.StoredProcedure
};
cmd.Parameters.AddWithValue("@UserId", userId);
using (var transaction = connection.BeginTransaction())
{
try {
transaction.Commit();
}
catch {
transaction.Rollback();
throw;
}
}
connection.BeginTransaction(IsolationLevel.ReadCommitted);
var blogs = context.Blogs
.Include(b => b.Posts)
.ToList();
context.BulkInsert(entities);
var pagedData = context.Products
.OrderBy(p => p.Id)
.Skip((pageNumber - 1) * pageSize)
.Take(pageSize)
.ToList();
- 考虑使用MemoryCache或分布式缓存
- 实现缓存失效机制
- 对频繁读取的静态数据使用缓存
[ProtectedPersonalData]
public string SocialSecurityNumber { get; set; }
- 启用EF Core的查询日志
- 使用SQL Server Profiler或扩展事件
optionsBuilder.UseSqlServer(connectionString)
.ConfigureWarnings(warnings => warnings
.Log(RelationalEventId.QueryClientEvaluationWarning)
.Log(RelationalEventId.QueryPossibleUnintendedUseOfEqualsWarning));
public interface IRepository<T> where T : class
{
Task<T> GetByIdAsync(int id);
Task<IEnumerable<T>> GetAllAsync();
Task AddAsync(T entity);
}
public class CreateProductCommand : IRequest<int>
{
public string Name { get; set; }
public decimal Price { get; set; }
}
public class GetProductsQuery : IRequest<List<ProductDto>>
{
public bool OnlyActive { get; set; }
}
var options = new DbContextOptionsBuilder<AppDbContext>()
.UseInMemoryDatabase(databaseName: "TestDb")
.Options;
var mockSet = new Mock<DbSet<Product>>();
var mockContext = new Mock<AppDbContext>();
mockContext.Setup(m => m.Products).Returns(mockSet.Object);
var strategy = context.Database.CreateExecutionStrategy();
strategy.Execute(() =>
{
using (var transaction = context.Database.BeginTransaction())
{
transaction.Commit();
}
});
services.AddDbContext<AppDbContext>(options =>
Configuration.GetValue<bool>("UsePostgres")
? options.UseNpgsql(connectionString)
: options.UseSqlServer(connectionString)
);