Reputation: 5
I faced a problem; it is necessary to read data from the devices using the modbus protocol. I can not understand how to write to database in ActionResult. Maybe someone can help.
public ActionResult Index(Sensors sensors)
{
Sensors snsr = new Sensors();
client = new ModbusClient(IpAddress, port);
client.Connect();
int[] response = client.ReadHoldingRegisters(StartAddress, quantity);
client.Disconnect();
for (int i = 0; i < quantity; i++)
{
string value0 = response[0].ToString();
string value1 = response[1].ToString();
string value2 = response[2].ToString();
ViewBag.stohome0 = value0;
ViewBag.stohome1 = value1;
ViewBag.stohome2 = value2;
snsr.sensorname = response[0];
db.Sensors.Add(snsr);
db.SaveChanges();
}
return View();
Upvotes: 0
Views: 124
Reputation: 24147
You need to create a new Sensors
object for every time that the for
-loop executes its body.
I tried to make things more clear by constructing a unique name for each sensor, instead of using the response[...] value for that. And I gave a suggestion of how to use the response[...] values.
for (int i = 0; i < quantity; i++)
{
Sensors snsr = new Sensors();
snsr.sensorname = "Sensor-" + i;
// Maybe also do something like...
// snsr.sensorvalue = response[i];
db.Sensors.Add(snsr);
db.SaveChanges();
}
Upvotes: 1