You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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 Sensors entity: You create snsr once 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 index i, and you're assigning an integer directly to sensorname (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:

  1. using statement for ModbusClient: This guarantees the client is cleaned up properly even if an error occurs, preventing resource leaks.
  2. Batch database save: We add all Sensors entries first, then call SaveChanges() once—this reduces database round trips and improves efficiency.
  3. Per-loop entity creation: Each iteration makes a new Sensors object, so Entity Framework can track each entry without conflicts.
  4. Proper value handling: We use the loop index i to access each register's value, and convert it to a string to match the sensorname property (adjust this if your property expects a different data type).
  5. 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, and quantity are properly initialized before this method runs (they look like class-level variables).
  • If your Sensors model has other required properties, make sure to populate them before adding the entity to the database.

内容的提问来源于stack exchange,提问作者Sunbro

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 09:04:26