使用Twilio发送消息后无法保存至数据库的技术咨询
Let's break down the issues here and fix them step by step:
1. You're not persisting changes to the database
The biggest problem is that you're only adding the message entity to the in-memory context with _context.Messages.Add(message), but you never actually save those changes to the database. You need to call _context.SaveChanges() after adding the entity to write it to your database.
2. Incorrect DbContext setup and management
Your ApplicationDbContext has a few issues that are causing the null value and thread-related debug message:
- The empty constructor and static
Create()method aren't configuring a database connection string. Without this, the context can't properly connect to your database, leading to unexpected null states. - Manually instantiating the context with
new ApplicationDbContext()in the controller isn't best practice—you should use dependency injection (DI) to manage the context's lifecycle, which avoids thread-related issues and ensures proper initialization.
3. Potential model binding and validation gaps
- Your view uses
@Html.HiddenFor(m => m.Message.Id)—for a new message, this will be set to the default value (usually0), which is fine ifIdis an auto-incrementing primary key, but make sure yourMessageclass configuresIdas such. - Also, note the typo:
Recievershould beReceiver(missing an "e"). While this won't break functionality, it's inconsistent with standard spelling and could cause confusion later.
Fixed Code Examples
Updated ApplicationDbContext
public class ApplicationDbContext : DbContext { public DbSet<Message> Messages { get; set; } // Constructor for dependency injection public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { } // Configure database connection (if not using DI for options) protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { if (!optionsBuilder.IsConfigured) { // Replace with your actual connection string from appsettings.json or config optionsBuilder.UseSqlServer("Server=(localdb)\\mssqllocaldb;Database=YourMessageDb;Trusted_Connection=True;"); } } }
Updated MessageController
public class MessageController : Controller { private readonly ApplicationDbContext _context; private readonly IMessageSender _messageSender; // Inject both context and message sender via constructor public MessageController(ApplicationDbContext context, IMessageSender messageSender) { _context = context; _messageSender = messageSender; } [ActionName("MessageStatus")] [HttpPost] // Explicitly mark as POST since this handles form submissions public ActionResult Send(Message message) { // Validate the model first if (!ModelState.IsValid) { var viewModel = new MessageViewModel { Message = message }; return View("New", viewModel); // Return to the form view with errors } _context.Messages.Add(message); _context.SaveChanges(); // Critical: Save to the database _messageSender.Send(message); var viewModel = new MessageViewModel { Message = message }; return View("MessageStatus", viewModel); } }
Corrected Message Class (example)
public class Message { public int Id { get; set; } // Auto-incrementing primary key public string Receiver { get; set; } // Fixed spelling public string Sender { get; set; } public string Body { get; set; } }
Debug Note
The "The function requires all threads to run" message typically pops up when the debugger tries to evaluate a value tied to a background thread. Fixing the DbContext initialization and using proper DI should resolve this, as the context will be properly instantiated and managed.
内容的提问来源于stack exchange,提问作者ibalgin orbit

