在ASP.NET MVC控制器中,可以使用以下方法来持久化数据:
public class MyDbContext : DbContext
{
public DbSet Users { get; set; }
}
public class UserController : Controller
{
private readonly MyDbContext _context;
public UserController(MyDbContext context)
{
_context = context;
}
public IActionResult Index()
{
var users = _context.Users.ToList();
return View(users);
}
public IActionResult Create(User user)
{
_context.Users.Add(user);
_context.SaveChanges();
return RedirectToAction("Index");
}
// 其他操作...
}
SqlConnection
和SqlCommand
类来连接和执行SQL命令。以下是一个使用ADO.NET的示例代码:public class UserController : Controller
{
private readonly string _connectionString;
public UserController(IConfiguration configuration)
{
_connectionString = configuration.GetConnectionString("DefaultConnection");
}
public IActionResult Index()
{
var users = new List();
using (var connection = new SqlConnection(_connectionString))
{
connection.Open();
var command = new SqlCommand("SELECT * FROM Users", connection);
var reader = command.ExecuteReader();
while (reader.Read())
{
var user = new User
{
Id = (int)reader["Id"],
Name = (string)reader["Name"],
// 其他属性...
};
users.Add(user);
}
}
return View(users);
}
public IActionResult Create(User user)
{
using (var connection = new SqlConnection(_connectionString))
{
connection.Open();
var command = new SqlCommand("INSERT INTO Users (Name) VALUES (@Name)", connection);
command.Parameters.AddWithValue("@Name", user.Name);
command.ExecuteNonQuery();
}
return RedirectToAction("Index");
}
// 其他操作...
}
无论使用哪种方法,都需要在Startup类的ConfigureServices
方法中注册相关的服务,例如:
services.AddDbContext(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
或者:
services.AddTransient(provider => Configuration);
以上代码中的DefaultConnection
是在appsettings.json文件中定义的数据库连接字符串。