.NET 4.5,实体框架6 - 创建/更新/修改/删除多对多

时间:2017-12-06 21:34:58

标签: entity-framework-6

假设我有2个模型,PeopleClass,CarsClass,我也在使用Lazy Loading。许多'人'可以拥有相同的'汽车'。如何更新处理该关系的关系?理想情况下,作为一个接口,但如果我必须在一个很好的控制器中做到这一点。

我知道有一个.add()和.attach()方法,但是你如何使用异步操作和延迟加载在具有EF的Web API 2 Controller中实现它(需要知道如何创建,添加,更新/修改和删除)?

我发现这也很好奇ppl认为解决方案:http://blog.brentmckendrick.com/introducing-graphdiff-for-entity-framework-code-first-allowing-automated-updates-of-a-graph-of-detached-entities/

代码示例:

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 virtual ICollection<Car> Cars { get; set; }
}

汽车类/型号:

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 virtual ICollection<People> Peoples { get; set; }
}

DbContext文件:

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

使用EF w / actions在我的异步控制器中需要做什么?我知道有一些方法叫做:clear,add,attach find等。但是我不清楚如何在GET,POST,PUT,DELETE控制器动作中实现。

自首次发布以来更新:

我使用EF + Async Actions让PUT在我的Web API 2 Controller中工作。我现在只需要知道如何进行删除。

// PUT: api/People/5
[ResponseType(typeof(void))]
public async Task<IHttpActionResult> People(int id, People peoples)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            if (id != peoples.Id)
            {
                return BadRequest();
            }

            var env = db.People
                .Include(p => p.Cars)
                .Single(q => q.Id == peoples.Id);

            db.Entry(env).CurrentValues.SetValues(peoples);

            foreach(var automobile in peoples.Cars)
            {
                db.Cars.Attach(automobile);
                env.Cars.Add(automobile);
            }

            //db.Entry(peoples).State = EntityState.Modified;

            try
            {
                await db.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!PeopleExists(id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return StatusCode(HttpStatusCode.NoContent);
        }

0 个答案:

没有答案