Corey
Corey

Reputation: 1793

Entity Framework 6 update a table and insert into foreign key related tables

Not quiet sure how to word the title for this one so feel free to edit if it isn't accurate.

Using an example, what I am trying to accomplish is update a record in table foo, and then create new records in a subsequent table that has the foo tables PK as foreign key, think One-to-Many relationship.

How do I update a table that has foreign key constraints and create a new related record(s) in these subsequent table(s)?

Currently I am using Entity Framework 6 to .Add and .Attach entities to the context and save them to the database.

Edit

To clarify further what I am trying to achieve, the below object is a cut down made up example what I am trying to save to the context. If I try to .Add intObj after "Billy Bob" has already been created because he has bought a new car, another service, or his tyres have changed it will create a new Billy Bob record (duplicate) and the corresponding related tables.

        intObj.FirstName = "Billy";
        intObj.Lastname = "Bob";
        intObj.Important = 100;
        intObj.LastSeen = DateTime.Now.Date;
        intObj.Cars = new List<Car>{
            new Car{
                Model = "Commodore",
                Make = "Holden",
                YearMade = DateTime.Today.Date,
                Odometer = 15000,
                EmailWordCount = 500,
                TyreStatuss = new List<TyreStatus>{
                    new TyreStatus{
                        Tyre1 = "Good",
                        Tyre2 = "Good",
                        Tyre3 = "Okay",
                        Tyre4 = "Okay"
                        }                                 
                },
                Services = new List<Service>{
                    new Service{
                        Cost = "$500",
                        Time = "2 Days",
                        Date = DateTime.Today
                    }
                },
            }
        };

Thanks

Upvotes: 4

Views: 7147

Answers (1)

E-Bat
E-Bat

Reputation: 4892

In the following snippets you have Employee class, which references two more entities: a collection of Assignment and a single Country.
ORMs like EF , NHibernate, etc... have a feature known as Transitive Persistence, that is, if an object (Assignment and Country) is referenced by a persistent one (Employee), then Assignments and Country will eventually become persistent too when, in your EF case, SaveChanges method gets invoked in the Context, without you explicitly save them.

    public class Employee
        {
            public virtual Guid Id { get; protected set; }
            public virtual string EmployeeNumber { get; set; }
            public virtual Country BirthCountry { get; set; }
            private ICollection<Assignment> _assignment = new List<Assignment>();
            public virtual ICollection<Assignment> Assignments
            {
                get
                {
                    return _assignment;
                }

                set
                {
                    _assignment= value;
                }
            }
        }

        public class Assignment
        {
            public virtual Guid Id { get; protected set; }
            public virtual DateTime BeginTime { get; set; }
            public virtual DateTime EndTime { get; set; }
            public virtual string Description{ get; set; } 
        }

        public class Country
        {
            public virtual Guid Id { get; protected set; }
            public virtual string Name { get; set; }
        }

   //Somewhere in your program      
   private void SaveAllChanges()
         {
             _db = new EFContext();
             //Creating a new employee here, but it can be one loaded from db
             var emp = new Employee { FirstName = "Emp Name", 
                 LastName = "Emp Last", EmployeeNumber = "XO1500"
             };
             emp.BirthCountry = new Country { Name = "Country1" };
             emp.Assignment.Add(new Assignment{ BeginTime = DateTime.Now,EndTime=DateTime.Now.AddHours(1) });

            //Only employee is explicitly added to the context
            _db.Employees.Add(emp); 
            //All the objects in the employee graph will be saved (inserted in this case) in the db. 
            _db.SaveChanges();
        }
    }

EDIT:

That is very similar to my code above, once "Billy Bob" is created you only need to update it, and that include any new service he buy;

Pseudo code:

var bob = _db.Clients.SingleOrDefault(c=> c.Id = "Bob Row Id")
//Bob buy a car:
bob.Cars.Add(new Car()...)
//...and change tire 1 from an old car
var car = bob.Cars.SingleOrDefault(c=> c.Id = "Car Row Id")
car.TireStatus.Tire1 = "New"
....

//Persist all changes
//Existing objects will be updated..., and the new ones created in this process will be inserted
_db.SaveChanges()

Let me know if this clarify your ideas

Upvotes: 4

Related Questions