如何在MVC控制器中写入数据?Modbus数据存入ActionResult数据库遇阻求助
Fixing Modbus Data Reading & Database Insertion in Your ActionResult
Hey there! Let's work through your Modbus-to-database issue step by step. Looking at your code, I spot several key issues that are likely causing unexpected behavior or errors—let's fix them up and make this work reliably.
First, let's break down the problems in your current code:
- Reusing the same
Sensorsentity: You createsnsronce outside the loop but try to add it to the database multiple times. Entity Framework will throw an error here because it already tracks that entity instance. - Wasted database calls: Calling
db.SaveChanges()inside the loop hits the database on every iteration, which is inefficient and slow. - Incorrect value assignment: You're hardcoding
response[0],response[1],response[2]in every loop iteration instead of using the loop indexi, and you're assigning an integer directly tosensorname(assuming that property is a string). - Redundant ViewBag assignments: Setting ViewBag values inside the loop means only the last iteration's values will be visible in the view.
Here's the corrected code with explanations:
public ActionResult Index(Sensors sensors) { // Use 'using' to ensure ModbusClient is properly disposed using (var client = new ModbusClient(IpAddress, port)) { client.Connect(); int[] response = client.ReadHoldingRegisters(StartAddress, quantity); client.Disconnect(); // Set ViewBag values once (outside loop) to avoid overwriting if (response.Length >= 3) { ViewBag.stohome0 = response[0].ToString(); ViewBag.stohome1 = response[1].ToString(); ViewBag.stohome2 = response[2].ToString(); } // Create a new Sensors instance for each register value for (int i = 0; i < response.Length; i++) { var snsr = new Sensors(); // Assign the current register's value (convert to string if needed) snsr.sensorname = response[i].ToString(); // Add to database context (tracked but not saved yet) db.Sensors.Add(snsr); } // Save all changes in one batch for better performance db.SaveChanges(); } return View(); }
Key improvements made:
usingstatement for ModbusClient: This guarantees the client is cleaned up properly even if an error occurs, preventing resource leaks.- Batch database save: We add all
Sensorsentries first, then callSaveChanges()once—this reduces database round trips and improves efficiency. - Per-loop entity creation: Each iteration makes a new
Sensorsobject, so Entity Framework can track each entry without conflicts. - Proper value handling: We use the loop index
ito access each register's value, and convert it to a string to match thesensornameproperty (adjust this if your property expects a different data type). - Fixed ViewBag assignment: Setting ViewBag values outside the loop ensures you retain the first three register values as intended.
Additional tips:
- Add try-catch blocks around the Modbus connection and database operations to handle cases where the device is unreachable or the database write fails.
- Double-check that
IpAddress,port,StartAddress, andquantityare properly initialized before this method runs (they look like class-level variables). - If your
Sensorsmodel has other required properties, make sure to populate them before adding the entity to the database.
内容的提问来源于stack exchange,提问作者Sunbro
相关产品推荐
相关产品推荐

