A referential integrity constraint violation has occurred

0

I'm getting this error every time I try to update an object in my SQL database via EntityFramework , the error is as follows:

  

A referential integrity constraint violation has occurred: Property values that define referential constraints are not consistent between parent and relationship-dependent objects.

The error only happens when I change the FK VideoID this way in Controller :

foo.Video = vid;
foo.VideoID = vid.VideoID;

If you do not change these values, the error does not happen, so something is wrong in this logic but I do not understand what. I pass the object foo to the method that does the update, which is as follows:

 public void UpdateCompany(Company foo)
    {

        Company c = GetCompany(foo.CompanyID);

        if (c.AddressID != null)
        {
            Address a = new AddressesManager().getAddress((Int32)c.AddressID);
            foo.Address.EntityKey = a.EntityKey;
        }

        if (c.VideoID != null)
        {
            Video v = new VideosManager().GetVideo((Int32)c.VideoID);
            foo.Video.EntityKey = v.EntityKey;
            context.Detach(c.Video);
        }

        if (c.Video1 != null)
        {
            Video v2 = new VideosManager().GetVideo((Int32)c.PreRoleID);
            foo.Video1.EntityKey = v2.EntityKey;
            context.Detach(c.Video1);
        }

        company.EntityKey = c.EntityKey;

        context.Detach(c.Address);
        context.Detach(c);

        try
        {
            context.AttachTo("Companies", foo);
            foo.SetAllModified(context);

            if (foo.Address != null)
            {
                context.AttachTo("Addresses", foo.Address);
                foo.Address.SetAllModified(context);
            }

            if (c.VideoID != null)
            {
                context.AttachTo("Videos", foo.Video);
                foo.Video.SetAllModified(context);
            }

            if (c.Video1 != null)
            {
                context.AttachTo("Videos", foo.Video1);
                foo.Video.SetAllModified(context);
            }

            // novo
            var qup = from p in context.CompanyProducts
                      where p.CompanyID == c.CompanyID
                      select p;

            if (qup.Count() != 0)
            {
                DataLibrary.CompanyProduct cp = qup.First();
                cp.RecordState = 1;
            }

            //novo
            context.SaveChanges();
        }
        catch (Exception e)
        {
            throw e;
        }

    }

Database Images:

    
asked by anonymous 04.01.2018 / 11:35

0 answers