0
I am getting this error every time I try to update an object in my SQL database via Entityframework, the error is as follows:
A reference integrity constraint violation occurred: Property values that define reference constraints are not consistent between main and relation dependent objects.
The mistake only happens when I change the FK Videoid in this way in the 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 realize what. I pass the object foo
for the update method, which is the following:
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;
}
}
Images from the database:
The error only happens when I change FK Videoid like this: foo.Video = Vid; foo.Videoid = Vid.Videoid; ??????? where did you do it??
– Marco Souza
Also publish the structure of the tables in question. Probably the Videoid column has no reference in another table.
– Motta
I honestly looked at that code of yours and I didn’t understand why it was so complicated.... you are using Lazy load certainly to have to keep attaching and detaching entities from the context that in my view has no need. Since you do the search from a company c = Getcompany(company.Companyid); ... use it which already has its context properties mapped .... only change what has been modified.
– Marco Souza
@Marconciliosouza I do it in Controller (in POST) and then I pass the object
foo
(which is a Company) for the following method. As to the question of the implementation of the update, I did not create it, it was already done and I also could not understand why it was done so... I will put a picture of the table– ihavenokia