Ef6: Create/Update/Modify/Delete Many to Many

Created on 6 Dec 2017  ·  2Comments  ·  Source: dotnet/ef6

Lets say I have 2 models, PeopleClass, CarsClass, also I am using Lazy Loading. Many 'People' can own the same 'Car'. How do I update the relationship to handle that? Ideally as an Interface, but if I have to do it in a Controller that is fine too.

I am aware there is an .add() and .attach() method, but how do you implement that in a Web API 2 Controller w/ EF using async actions and lazy loading (need to know how to create, add, update/modify, and delete)?

I found this as well: http://blog.brentmckendrick.com/introducing-graphdiff-for-entity-framework-code-first-allowing-automated-updates-of-a-graph-of-detached-entities/

_Code Example:_

People Class/Model:

public class People
    {
        public People()
        {
            this.Cars = new HashSet<Car>();
        }

        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        [Key]
        public int Id { get; set; }
        public string PeopleName { get; set; }
        public int? CarId { get; set; }
        public virtual Car Cars { get; set; }
        public virtual ICollection<Car> Cars { get; set; }
}

Car Class/Model:

public class Car
    {
        public Car()
        {
            this.Peoples = new HashSet<People>();
        }

        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        [Key]
        public int Id { get; set; }
        public string CarName { get; set; }
        public int? PeopleId { get; set; }
        public virtual People Peoples { get; set; }
        public virtual ICollection<People> Peoples { get; set; }
}

DbContext file:

public DbSet<People> Peoples { get; set; }
        public DbSet<Car> Cars { get; set; }
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<People>()
                  .HasMany(c => c.Cars) 
                  .WithMany(t => t.Peoples)
                  .Map(m => { 
                        m.ToTable(“PeopleCars”);
                        m.MapLeftKey(“PeopleId”); 
                        m.MapRightKey(“CarId”); 
              });
}

What do I have to do in my async controller using EF w/ actions? I know there are methods called: _clear, add, attach find_ etc. But I am unclear how to implement in GET, POST, PUT, DELETE controller actions.

closed-question

All 2 comments

May be that's a kind of question that should be asked on stack overflow

@joehoeller Some links to help you get started:

Was this page helpful?
0 / 5 - 0 ratings