Answer the question
In order to leave comments, you need to log in
What is the correct way to update a record in Entity Framework 6?
There is a trace. the code.
public class Switcher
{
[Key]
public int ID { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string IP { get; set; }
[Required]
public SwitcherModel Model { get; set; }
[Required]
public string FirmwareVersion { get; set; }
public List<Port> ScanPorts { get; set; }
}
public class Port
{
[Key]
public int ID { get; set; }
public string Name { get; set; }
[Required]
public byte Number { get; set; }
[NotMapped]
public bool IsLink { get; set; }
}
public void UpdateSwitcher(Switcher switcher)
{
using (var db = new MonitoringSwitcherContext())
{
var switcherFind = db.Switchers.Find(switcher.ID);
if (switcherFind == null)
db.Switchers.Add(switcher);
else
{
// Проходится по всем полям и связям
switcherFind.Name = switcher.Name;
switcherFind.IP = switcher.IP;
switcherFind.Model = switcher.Model;
switcherFind.FirmwareVersion = switcher.FirmwareVersion;
foreach (var port in switcher.ScanPorts)
{
var portExist = switcherFind.ScanPorts.Find(p => p.ID == port.ID);
if (portExist != null)
{
portExist.Name = port.Name;
portExist.Number = port.Number;
}
else
switcherFind.ScanPorts.Add(port);
}
}
db.SaveChanges();
}
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question