Entity Framework - Updating relationship by changing foreign key

前端 未结 2 844
别那么骄傲
别那么骄傲 2021-02-06 02:32

I have the two following models and DbContext:

    public class TestDbContext : DbContext
    {
        public IDbSet People { get; set; }
              


        
2条回答
  •  梦毁少年i
    2021-02-06 03:02

    Try something like this :

        using (TestDbContext context = new TestDbContext())
                {
                    foreach (Person person in People)
                    {
                        if (!(context.People.Any(p => p.ID == person.ID)))
                            context.People.Add(person);
                        else
                        {
                            context.People.Attach(person);
                            context.Entry(person).State = System.Data.EntityState.Modified;
                        }
                        context.SaveChanges();
                    }
                    foreach (Car caar in Cars)
                    {
                        if (!(context.Cars.Any(c => c.ID == caar.ID)))
                            context.Cars.Add(caar);
                        else
                        {
                            context.Cars.Attach(caar);
                            context.Entry(caar).State = System.Data.EntityState.Modified;
                        }
                        context.SaveChanges();
                    }
    
                }
    

    I think your error is due to the context.SaveChanges placements (and partialy your architecture). Consider using a dedicated method (a basic CRUD for instance) for each operation on your DB via Entity Framework. Hope this helps.

    Edit : With a CRUD approch :

    public class PersonManager // CRUD
        {
            public void Create(Person person)
            {
                using (TestDbContext context = new TestDbContext())
                {
                    context.Person.Add(person);
                    context.SaveChanges();
                }
            }
    
            public void Update(Person person)
            {
                using (TestDbContext context = new TestDbContext())
                {
                    context.Person.Attach(person);
                    context.Entry(person).State = System.Data.EntityState.Modified;
                    context.SaveChanges();
                }
            }
        }
    

    You could also make this class static in order to fit to your architecture.

提交回复
热议问题