执行db.SaveChanges失败,请求排查EF上下文及控制器代码问题
Hey there, let's dig into why your db.SaveChanges() call is failing. First off, I notice your Create method in TourController.cs is incomplete—let's fix that first, then walk through common issues that cause this error.
Step 1: Complete & Improve the Create Method
Right now your code cuts off at db.Tours....—let's flesh it out with proper context handling, model validation, and error catching so you can see exactly what's going wrong:
// POST: /Tour/Create [HttpPost] public ActionResult Create(Tour tour) { // First, check if the submitted model is valid if (!ModelState.IsValid) { // Send the user back to the form with validation errors return View(tour); } try { // Use a using block to ensure the DbContext is properly disposed using (var db = new MyDbContext()) { db.Tours.Add(tour); db.SaveChanges(); // This is where your error was happening return RedirectToAction("Index"); // Redirect to tour list on success } } catch (Exception ex) { // Capture the exact error message and show it to you ModelState.AddModelError("", $"Failed to save tour: {ex.Message}"); // Include inner exception if it exists—often has more details if (ex.InnerException != null) { ModelState.AddModelError("", $"Inner error: {ex.InnerException.Message}"); } return View(tour); } }
If you're using a class-level db field in your controller (instead of the using block), make sure it's initialized correctly:
private readonly MyDbContext _db = new MyDbContext(); // Then in Create: _db.Tours.Add(tour); _db.SaveChanges();
Step 2: Verify Your Connection String
Your MyDbContext uses the connection string named "ExploreCalifornia"—check your Web.config to make sure it's correctly configured:
<connectionStrings> <add name="ExploreCalifornia" connectionString="Data Source=(localdb)\mssqllocaldb;Initial Catalog=ExploreCalifornia;Integrated Security=True" providerName="System.Data.SqlClient" /> </connectionStrings>
- Confirm the database
ExploreCaliforniaexists (you can create it via EF migrations withUpdate-Databasein Package Manager Console if using Code First) - Ensure the data source matches your SQL Server instance (e.g.,
localhost\SQLEXPRESSinstead of localdb if you're using a full SQL Server)
Step 3: Check Your Tour Model for Validation Issues
If your Tour class has data annotations (like [Required], [StringLength], or foreign key constraints), missing or invalid values will cause SaveChanges to fail. For example:
public class Tour { public int Id { get; set; } [Required(ErrorMessage = "Tour name is required")] [StringLength(100, ErrorMessage = "Name can't be longer than 100 characters")] public string Name { get; set; } // Example foreign key—make sure the related entity exists if this is set public int? RegionId { get; set; } public Region Region { get; set; } }
The ModelState.IsValid check we added earlier will catch these issues before even trying to save to the database.
Step 4: Check Database Permissions & Constraints
- If you're using SQL Server, make sure the application pool identity (or the user your app is running as) has read/write permissions to the
ExploreCaliforniadatabase - Ensure there are no database-level constraints being violated (e.g., duplicate primary keys, missing required columns that aren't enforced by your model)
Once you've updated your code with error catching, run the Create action again— the exception message will tell you exactly what's broken (whether it's a connection issue, invalid data, or something else).
内容的提问来源于stack exchange,提问作者jdotdoe

