C# Entity Speichern oder Update von Objekten

Einfaches Abspeichern von Objekten, oder ein Update wenn vorhanden:

class Car
    {
        public int id { get; set; }

        public string name { get; set; }

        public double weight { get; set; }

        public DateTime carEntryDate { get; set; }
    }


    class ClassCar
    {
        private async Task SaveUpdateCar(Car car = null)
        {
            try
            {
                //open connection
                using (var db = new dbEntities())
                {
                    //new object of data 
                    var thCar = new Car();

                    //on update fill the object with the given data 
                    //ie the unique id
                    if (car != null)
                    {
                        thCar = db.zahlungen.Find(car.id);
                    }
                    
                    //set the properties to object if ther is a new object
                    else
                    {
                        thCar.carEntryDate = DateTime.Now;
                    }
                    
                    //fill the object with new data
                    car.name = "Audi SQ7";
                    car.weight = 1980;

                        
                        //if add a new object
                    if (car == null)
                    {
                        db.kalkulation_zahlungen.Add(thCar);
                    }
                    //save the data to db oder save async
                    db.SaveChangesAsync();                   
                }
            }
            catch (Exception ex)
            {
                var fail = ex.Message;
            }
        }
    }

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert