M
M
murad882014-10-20 20:37:00
ORM
murad88, 2014-10-20 20:37:00

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();
                }
        }

How to correctly update the Switchers entry so that all its properties and relationships are replaced with new values.
Alternatively, you can delete an entry and all of its links (cascade delete), then add a new entry.
Or you need to manually go through all the fields and links and change the values ​​(the code will turn out to be quite cumbersome, especially if there are a lot of links).

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Y
Yuri, 2014-10-21
@Gilga

db.Switchers.AddOrUpdate(switcher);
db.SaveChanges();

Or
db.Entry(switcher).State = EntityState.Modified;
db.SaveChanges();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question