none
How to update many to many in EF 4.4 ??? RRS feed

  • Question

  • Is it possible to update many to many in EF 4.4 it is 5.0 but running in .net 4.0 so 4.4...

    I have tryed with this:

     using (var context = new CampingForumEntities1())
                {
                    Udlejning udl = context.Udlejnings.FirstOrDefault(d => d.UdlejningId == u.UdlejningId);//Old
                    //List<vogn_udlejning> vuList = udl.vogn_udlejning.ToList();
                    //List<produkt_udlejning> puList = udl.produkt_udlejning.ToList();
    
                    if (udl != null)
                    {
                        foreach (ExtendedGasAntalVognIds egavi in pu)
                        {
                            if (egavi.gasKg != "0")
                               u.produkt_udlejning.Add(new produkt_udlejning
                                {
                                    Antal = egavi.antal,
                                    produkt_id = context.Produkters.Where(g => g.Type == egavi.gasKg && g.CategoryId == 1).FirstOrDefault().id,
                                    Produkter = context.Produkters.Where(g => g.Type == egavi.gasKg && g.CategoryId == 1).FirstOrDefault(),
                                    udlejning_id = u.UdlejningId,
                                    Udlejning = u,
                                    VognIds = egavi.vognIds
                                });
                        }
    
                        //context.Entry(puList).CurrentValues.SetValues(u.produkt_udlejning);
    
                        var vogne = context.Vogns.Where(v => vu.Keys.Contains(v.Nummerplade)).ToList();
    
                        foreach (Vogn v in vogne)
                        {
    
                            bool NrpladeFortelt = vu.FirstOrDefault(k => k.Key == v.Nummerplade).Value;
    
                            if (NrpladeFortelt)
                            {
                                u.vogn_udlejning.Add(new vogn_udlejning
                                {
                                    Vogn = v,
                                    vogn_id = v.Id,
                                    Udlejning = u,
                                    udlejning_id = u.UdlejningId,
                                    Fortelt = NrpladeFortelt
                                });
                            }
                            else
                            {
                                u.vogn_udlejning.Add(new vogn_udlejning
                                {
                                    Vogn = v,
                                    vogn_id = v.Id,
                                    Udlejning = u,
                                    udlejning_id = u.UdlejningId,
                                    Fortelt = NrpladeFortelt
                                });
                            }
                        }
    
                        //context.Entry(vuList).CurrentValues.SetValues(u.vogn_udlejning);
    
    
                        u.UdlejningId = udl.UdlejningId;
                        context.Entry(udl).CurrentValues.SetValues(u);
                        context.SaveChanges();
                    }
                    
                }

    But with no luck thank you in advance...:)

    Wednesday, February 20, 2013 7:31 PM

All replies

  • Hi Simpa151,

    Welcome to the MSDN forum.

    Is the Udlejning and the Vogn the many to many relationship? Do you use database first approach?

    I think you are not required to set the join table manually. If you want to add Udlejnings in Vogn or add Vogns in Udlejning, you just add them directly. What specific error did you get?

    Best Regards,


    Alexander Sun [MSFT]
    MSDN Community Support | Feedback to us
    Develop and promote your apps in Windows Store
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    Friday, February 22, 2013 3:16 AM
  • I always code first because i just hate the sql EF generates...the error i get is:

    Multiplicity constraint violated. The role 'x' of the relationship 'many_many_relation_ibfk_2' has multiplicity 1 or 0..1.

    and i have changed the code a bit since...

    public static void OpdaterUdlejning(Udlejning u, Dictionary<string, bool> vu, List<ExtendedGasAntalVognIds> pu)
            {
                using (var context = new CampingForumEntities1())
                {
                    Udlejning udl = context.Udlejnings.FirstOrDefault(d => d.UdlejningId == u.UdlejningId);//Old
                                   
                    //List<vogn_udlejning> vuList = udl.vogn_udlejning.ToList();
                    List<vogn_udlejning> newvuList = new List<vogn_udlejning>();
                    ////List<produkt_udlejning> puList = udl.produkt_udlejning.ToList();
                    List<produkt_udlejning> newpuList = new List<produkt_udlejning>();
    
                    udl.produkt_udlejning.Clear();
                    udl.vogn_udlejning.Clear();
    
                    //foreach (vogn_udlejning vui in vuList)
                    //{
                    //    //context.vogn_udlejning.Attach(vui);
                    //    //context.vogn_udlejning.Remove(vui);
    
                    //    ((IObjectContextAdapter)context).ObjectContext.Detach(vui);
                    //    context.Entry(vui).State = System.Data.EntityState.Modified;
                    //}
    
                    //foreach (produkt_udlejning pui in puList)
                    //{
                    //    //context.produkt_udlejning.Attach(pui);
                    //    //context.produkt_udlejning.Remove(pui);
    
                    //    ((IObjectContextAdapter)context).ObjectContext.Detach(pui);
                    //    context.Entry(pui).State = System.Data.EntityState.Modified;
                    //}
    
    
    
    
                    if (u != null)
                    {
                        foreach (ExtendedGasAntalVognIds egavi in pu)
                        {
                            if (egavi.gasKg != "0")
                                u.produkt_udlejning.Add(new produkt_udlejning
                                  {
                                      Antal = egavi.antal,
                                      produkt_id = context.Produkters.Where(g => g.Type == egavi.gasKg && g.CategoryId == 1).FirstOrDefault().id,
                                      Produkter = context.Produkters.Where(g => g.Type == egavi.gasKg && g.CategoryId == 1).FirstOrDefault(),
                                      udlejning_id = u.UdlejningId,
                                      Udlejning = u,
                                      VognIds = egavi.vognIds
                                  });
                                //context.produkt_udlejning.Attach(new produkt_udlejning
                                //{
                                //    Antal = egavi.antal,
                                //    produkt_id = context.Produkters.Where(g => g.Type == egavi.gasKg && g.CategoryId == 1).FirstOrDefault().id,
                                //    Produkter = context.Produkters.Where(g => g.Type == egavi.gasKg && g.CategoryId == 1).FirstOrDefault(),
                                //    udlejning_id = u.UdlejningId,
                                //    Udlejning = u,
                                //    VognIds = egavi.vognIds
                                //});
    
                            newpuList.Add(new produkt_udlejning
                            {
                                Antal = egavi.antal,
                                produkt_id = context.Produkters.Where(g => g.Type == egavi.gasKg && g.CategoryId == 1).FirstOrDefault().id,
                                Produkter = context.Produkters.Where(g => g.Type == egavi.gasKg && g.CategoryId == 1).FirstOrDefault(),
                                udlejning_id = u.UdlejningId,
                                Udlejning = u,
                                VognIds = egavi.vognIds
                            });
    
                                //udl.produkt_udlejning.Add(new produkt_udlejning
                                //{
                                //    Antal = egavi.antal,
                                //    produkt_id = context.Produkters.Where(g => g.Type == egavi.gasKg && g.CategoryId == 1).FirstOrDefault().id,
                                //    Produkter = context.Produkters.Where(g => g.Type == egavi.gasKg && g.CategoryId == 1).FirstOrDefault(),
                                //    udlejning_id = u.UdlejningId,
                                //    Udlejning = u,
                                //    VognIds = egavi.vognIds
                                //});
                        }
    
                        OpdaterUdlejningProduktUdlejning(newpuList, udl.UdlejningId);
    
                        //context.Entry(u.produkt_udlejning).State = System.Data.EntityState.Modified;
                        //context.Entry(puList).CurrentValues.SetValues(u.produkt_udlejning);
    
                        var vogne = context.Vogns.Where(v => vu.Keys.Contains(v.Nummerplade)).ToList();
    
                        foreach (Vogn v in vogne)
                        {
    
                            bool NrpladeFortelt = vu.FirstOrDefault(k => k.Key == v.Nummerplade).Value;
    
                            if (NrpladeFortelt)
                            {
                                u.vogn_udlejning.Add(new vogn_udlejning
                                {
                                    Vogn = v,
                                    vogn_id = v.Id,
                                    Udlejning = u,
                                    udlejning_id = u.UdlejningId,
                                    Fortelt = NrpladeFortelt
                                });
    
                                //context.vogn_udlejning.Attach(new vogn_udlejning
                                //{
                                //    Vogn = v,
                                //    vogn_id = v.Id,
                                //    Udlejning = u,
                                //    udlejning_id = u.UdlejningId,
                                //    Fortelt = NrpladeFortelt
                                //});
    
                                newvuList.Add(new vogn_udlejning
                                {
                                    Vogn = v,
                                    vogn_id = v.Id,
                                    Udlejning = u,
                                    udlejning_id = u.UdlejningId,
                                    Fortelt = NrpladeFortelt
                                });
    
                                //udl.vogn_udlejning.Add(new vogn_udlejning
                                //{
                                //    Vogn = v,
                                //    vogn_id = v.Id,
                                //    Udlejning = u,
                                //    udlejning_id = u.UdlejningId,
                                //    Fortelt = NrpladeFortelt
                                //});
                            }
                            else
                            {
                                u.vogn_udlejning.Add(new vogn_udlejning
                                {
                                    Vogn = v,
                                    vogn_id = v.Id,
                                    Udlejning = u,
                                    udlejning_id = u.UdlejningId,
                                    Fortelt = NrpladeFortelt
                                });
    
                                //context.vogn_udlejning.Attach(new vogn_udlejning
                                //{
                                //    Vogn = v,
                                //    vogn_id = v.Id,
                                //    Udlejning = u,
                                //    udlejning_id = u.UdlejningId,
                                //    Fortelt = NrpladeFortelt
                                //});
    
                                newvuList.Add(new vogn_udlejning
                                {
                                    Vogn = v,
                                    vogn_id = v.Id,
                                    Udlejning = u,
                                    udlejning_id = u.UdlejningId,
                                    Fortelt = NrpladeFortelt
                                });
    
                                //udl.vogn_udlejning.Add(new vogn_udlejning
                                //{
                                //    Vogn = v,
                                //    vogn_id = v.Id,
                                //    Udlejning = u,
                                //    udlejning_id = u.UdlejningId,
                                //    Fortelt = NrpladeFortelt
                                //});
                            }
                        }
    
                        OpdaterUdlejningVognUdlejning(newvuList, udl.UdlejningId);
    
                        //((System.Data.Entity.Infrastructure.IObjectContextAdapter)udl).ObjectContext.Detach(vu2);
                        //context.Entry(vu2).State = System.Data.EntityState.Modified;
                       
                                           
    
                        u.UdlejningId = udl.UdlejningId;
                        context.Entry(udl).CurrentValues.SetValues(u);
                        //context.Entry(puList).CurrentValues.SetValues(newpuList);
                        //context.Entry(vuList).CurrentValues.SetValues(newvuList);
                       
                       
                        context.SaveChanges();
                    }
                   
                }
            }
    
            public static void OpdaterUdlejningVognUdlejning(List<vogn_udlejning> vuList, int uid)
            {
                using (var context = new CampingForumEntities1())
                {
                    var udlVu = context.Udlejnings.Include("vogn_udlejning").FirstOrDefault(d => d.UdlejningId == uid);//Old
                   
                    udlVu.vogn_udlejning.Clear();
    
                    foreach (vogn_udlejning vu in vuList)               
                        udlVu.vogn_udlejning.Add(vu);
    
                    context.SaveChanges();
                }
            }
    
            public static void OpdaterUdlejningProduktUdlejning(List<produkt_udlejning> puList, int uid)
            {
                using (var context = new CampingForumEntities1())
                {
                    var udlPu = context.Udlejnings.Include("produkt_udlejning").FirstOrDefault(d => d.UdlejningId == uid);//Old
                    List<produkt_udlejning> tempList = udlPu.produkt_udlejning.ToList();
    
                    udlPu.produkt_udlejning.Clear();
    
                    foreach (produkt_udlejning pu in puList)
                    {
                        //context.produkt_udlejning.Attach(pu);
                        //context.Entry(pu).State = System.Data.EntityState.Modified;
                        udlPu.produkt_udlejning.Add(pu);
                    }         
    
                        context.SaveChanges();               
                }
            } 

    and yes it is many to many... One rent can have lot of wagons...
    • Edited by Simpa151 Friday, February 22, 2013 9:07 AM
    Friday, February 22, 2013 9:03 AM
  • The exception message seems to be telling you that the relationship is not many-to-many. Which is probably an error in your mapping if it really is many to many.

    When code first generated your database did it actually create the tables as you would expect, with a join table for the many to many relationship? You could also use the power tools to view a read only diagram of your model, which would show if EF thinks the relationship is many-to-many or not.

    I suspect this is a problem with your mappings, either with the conventions not doing what you want or explicit configuration in OnModelCreating. Can you check them, and maybe show them here if you can't find anything?


    We are seeing a lot of great Entity Framework questions (and answers) from the community on Stack Overflow. As a result, our team is going to spend more time reading and answering questions posted on Stack Overflow. We would encourage you to post questions on Stack Overflow using the entity-framework tag. We will also continue to monitor the Entity Framework forum.

    Tuesday, February 26, 2013 5:47 PM
    Moderator
  • the mappings are Udlejning 1 - * vogn_udlejning * - 1 Vogn

    the same with      Udlejning 1 - * produkt_udlejning* - 1 Produkt

    but i gave up on EF in this so I wrote my own sql...the solution is:

    public static void TilføjVognUdlejning(vogn_udlejning vu)
            {
                using (var context = new CampingForumEntities1())
                {
                    //((IObjectContextAdapter)context).ObjectContext.Detach(vu);
    
                    context.vogn_udlejning.Attach(vu);
                    context.SaveChanges();
                }
            }
    
            //public static void FjernVognUdlejning(Udlejning u, vogn_udlejning vu)
            //{
            //    using (var context = new CampingForumEntities1())
            //    {
            //        context.vogn_udlejning.Remove(vu);
    
            //        context.Udlejnings.Add(u);
            //        context.SaveChanges();
            //    }
            //}
    
            public static void OpdaterProduktUdlejning(produkt_udlejning pu)
            {
                using (var context = new CampingForumEntities1())
                {
                    //((IObjectContextAdapter)context).ObjectContext.Detach(pu);
                    
                    context.produkt_udlejning.Attach(pu);
                    context.SaveChanges();
                }       
            }
            
            public static void OpdaterUdlejning(Udlejning u, Dictionary<string, bool> vu, List<ExtendedGasAntalVognIds> pu)
            {
                using (var context = new CampingForumEntities1())
                {
                    if (u != null)
                    {
                        Udlejning udl = context.Udlejnings.FirstOrDefault(d => d.UdlejningId == u.UdlejningId);//Old
    
                        udl.produkt_udlejning.Clear();
                        u.produkt_udlejning.Clear();
                        udl.vogn_udlejning.Clear();
                        u.vogn_udlejning.Clear();
    
                        u.UdlejningId = udl.UdlejningId;
                        context.Entry(udl).CurrentValues.SetValues(u);
                        context.SaveChanges(); 
    
                        //List<vogn_udlejning> vuList = udl.vogn_udlejning.ToList();
                        //List<produkt_udlejning> puList = udl.produkt_udlejning.ToList();
    
                        List<vogn_udlejning> newvuList = new List<vogn_udlejning>();
                        List<produkt_udlejning> newpuList = new List<produkt_udlejning>();
    
                    
                        foreach (ExtendedGasAntalVognIds egavi in pu)
                        {
                            if (egavi.gasKg != "0")
                                newpuList.Add(new produkt_udlejning
                                {
                                    Antal = egavi.antal,           //AsNoTracking()
                                    produkt_id = context.Produkters.AsNoTracking().Where(g => g.Type == egavi.gasKg && g.CategoryId == 1).FirstOrDefault().id,
                                    Produkter = context.Produkters.AsNoTracking().Where(g => g.Type == egavi.gasKg && g.CategoryId == 1).FirstOrDefault(),
                                    udlejning_id = u.UdlejningId,
                                    Udlejning = u,
                                    VognIds = egavi.vognIds
                                });
                        }
    
                       
                        foreach (produkt_udlejning newpu in newpuList)
                        {
                            //u.produkt_udlejning.Add(newpu);
                            //OpdaterProduktUdlejning(newpu);
                            context.Database.ExecuteSqlCommand("insert into produkt_udlejning(produkt_id, udlejning_id, Antal, VognIds) values(" + "@produkt_id" + "," + "@udlejning_id" + "," + "@Antal" + "," + "@VognIds" + ")",
                                new SqlParameter("produkt_id", newpu.produkt_id), new SqlParameter("udlejning_id", newpu.udlejning_id), new SqlParameter("Antal", newpu.Antal), new SqlParameter("VognIds", newpu.VognIds));
                        }
    
                                    //context.Vogns.AsNoTracking().Where(v => vu.Keys.Contains(v.Nummerplade)).ToList();
                        var vogne = context.Vogns.Where(v => vu.Keys.Contains(v.Nummerplade)).ToList();
    
                        foreach (Vogn v in vogne)
                        {
                            bool NrpladeFortelt = vu.FirstOrDefault(k => k.Key == v.Nummerplade).Value;
                            
                            newvuList.Add(new vogn_udlejning
                            {
                                Vogn = v,
                                vogn_id = v.Id,
                                Udlejning = u,
                                udlejning_id = u.UdlejningId,
                                Fortelt = NrpladeFortelt
                            });
                        }
    
                        
                        foreach (vogn_udlejning newvu in newvuList)
                        {
                            //u.vogn_udlejning.Add(newvu);
                            //TilføjVognUdlejning(newvu);
                            context.Database.ExecuteSqlCommand("insert into vogn_udlejning(vogn_id, udlejning_id, Fortelt) values(" + "@vogn_id" + "," + "@udlejning_id" + "," + "@Fortelt" + ")",
                                new SqlParameter("vogn_id", newvu.vogn_id), new SqlParameter("udlejning_id", newvu.udlejning_id), new SqlParameter("Fortelt", newvu.Fortelt));
                        }
                    }
                }
            }


    To prevent these errors:

    /*
    * errors occured
    * 1. An entity object cannot be referenced by multiple instances of IEntityChangeTracker.
    * 2. update many to many entity framework error: Multiplicity constraint violated. The role 'x' of the relationship 'many_many_relation_ibfk_2' has multiplicity 1 or 0..1.
    * 3. An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key.
    */

    • Edited by Simpa151 Tuesday, February 26, 2013 11:26 PM
    Tuesday, February 26, 2013 11:21 PM