Deleting Entity with Foreign Key Relationship Without Deleting Reference Object - asp.net-mvc

My problem is with the generic "Delete" in the BidController I am getting the typical Error:
The DELETE statement conflicted with the REFERENCE constraint "fkw_....". The conflict occurred in database table ..., column ....
The statement has been terminated.
Thank you so much for any and all help.

Try updating the ActiveBidId with a null value and then delete the bids.That way you break the link between the Item and Bid and than you can remove the Data from Bids.

Try making the relationship as OPTIONAL. This way your items can have null Foreign Keys.
If you are using database first approach:
CREATE TABLE Item(
ItemId INT PRIMARY KEY,
ActiveBidId INT NULL FOREIGN KEY REFERENCES Bid(BidId)
// ...
);
If you already created the table, then you can alter your table as follows:
ALTER TABLE Item
DROP CONSTRAINT FK_ActiveBidConstraint -- The name of your constraint
GO
ALTER TABLE Item
ADD CONSTRAINT FK_ActiveBidConstraint FOREIGN KEY (ActiveBidId) -- The name of your constraint
REFERENCES Bid(BidId);

Apparently I am able to set the GUID to null, so I am posting a simple answer.
In my BidController I have updated my code:
item = null;
This removes the reference to the bid and so the bids are free to be removed!

Related

MySQL import. #1452 - Cannot add or update a child row: a foreign key constraint fails

I've tried importing an SQL file into an empty database in PHP MyAdmin and I have been presented with the following error:
SQL query:
customer_eav_attribute` ADD CONSTRAINT `FK_CSTR_EAV_ATTR_ATTR_ID_EAV_ATTR_ATTR_ID`
FOREIGN KEY (`attribute_id`)
REFERENCES `eav_attribute` (`attribute_id`)
ON DELETE CASCADE ON UPDATE CASCADE
MySQL said: Documentation
#1452 - Cannot add or update a child row:
a foreign key constraint fails (`example_db_name`.
`#sql-1ab1_b9d4`, CONSTRAINT `FK_CSTR_EAV_ATTR_ATTR_ID_EAV_ATTR_ATTR_ID`
FOREIGN KEY (`attribute_id`) REFERENCES
`eav_attribute` (`attribute_id`) ON DELETE
CASCADE ON UPDATE CASCA)
I have no idea what it means, what do I need to do to fix this?
thank you :)
might be due to the order of the create table statement in the SQL file, move the create statement of the reference table "eav_attribute" before add constraint statements

rails & postgreSQL - How can I update a data with existing primary key?

I want to update some data in Lecture(id, name, etc.) table.
For example, there is a data(id: 1, name: "first") in the Lecture.
When I typed Lecture.create(id: 1, name: "newer") =>
PG::UniqueViolation: ERROR: duplicate key value violates unique constraint "lectures_pkey"
Is there any way to update data?
Try this:
Lecture.find(1).update(name: "newer")
Find more information on update here: http://guides.rubyonrails.org/active_record_basics.html#update
The reason it didn't work is because the id is unique. When you were using create, it was trying to create a NEW record with id of 1, not edit the same record.
PG::UniqueViolation: ERROR: duplicate key value violates unique
constraint "lectures_pkey"
id is the default primary key which shouldn't be changed or duplicated. As you are inserting a row with an existing id, you get that error.
Instead, you need to do like below.
#lecture = Lecture.find(1)
#lecture.update_attributes(name: "newer")
You can use
lec = Lecture.find(1)
lec.update_attributes(name: "newer")
You are getting error PG::UniqueViolation: ERROR: duplicate key value violates unique constraint "lectures_pkey" due to you can not create record with same id. Id is primary key in table.
All of the current answers are correct if you don't mind loading the record and then updating it. If you don't need to actually load the record, and just want to update data in the database you can do
Lecture.where(id: 1).update_all(name: "newer")
This will skip all validations, etc and just do a direct sql update of the data in the database of the record with id == 1

Update part of primary key Entity Framework 4.0

I've a table with a compose primary key (3 columns):
UTP_ID (ITEMId)
UTS_ID (CategoryID)
USS_ID (SubCategoryID)
When I try to change SubCategory ,for example,with EF 4 i get follow error:
utl.USS_ID = Convert.ToInt32(ddlSubSetor.SelectedItem.Value);
the property is part of the object's key information and cannot be modified
Any Ideias?Why i can't change it?
EF implements an Identity Map between primary key property values and object references. It doesn't allow to change the key for the same object instance.
I would do this with direct SQL:
objectContext.ExecuteStoreCommand(
"UPDATE MyTable SET USS_ID = {0} WHERE UTP_ID = {1} AND UTS_ID = {2} AND USS_ID = {3}",
Convert.ToInt32(ddlSubSetor.SelectedItem.Value),
utl.UTP_ID, utl.UTS_ID, utl.USS_ID);
Make sure that your entity utl is detached from the context because this code directly writes into the database table and the entity doesn't get any information about this change. But this avoids having to delete and recreate the entity (which might be impossible due to existing foreign key constraints on the old row in the database).
As a result of being part of the entity key the object needs to be deleted from the context and re-attached with the new primary key value.
The Entity Framework works by having a context which manages the state of the entities, a collection of entities (basically the table) and the entity itself (a row of data). As data is read from the database it is added to the entity's collection which in turn is managed by the context for changes of state. Changing an Entity's key is really deleting the entry from the database and inserting a new one. As a result to change an entity key, first delete the entity from it's collection, detach the entity object to allow key modification, change the primary key value and re-attach the entity to the collection. Finally call save changes in the context to apply the changes to the database.
The following code should produce the desired results:
Context.UTLs.DeleteObject(utl);
Context.UTLs.Detach(utl);
Context.SaveChanges();
utl.USS_ID = Convert.ToInt32(ddlSubSetor.SelectedItem.Value);
Context.UTLs.AddObject(utl).
Context.SaveChanges();

Symfony - Try to update a record in DB with some foreign keys

Thanks a lot for recent help. It works really well, but now I am having some problems with this code.
//Save course record to DB
$record_course = new course();
$record_course->setName($courseInfo['name']);
$record_course->setUrl($courseInfo['url']);
$record_course->setAcronym($courseInfo['acronym']);
$record_course->setCourseTypeId($record_courseType->getId());
$record_course->setStartDate($courseInfo['startDate']);
$record_course->setCollegeId($record_college->getId());
$record_course->setPlanUrl($courseInfo['planUrl']);
$record_course->replace();
As you can see, I try to update a record but now we have some foreign keys. In this case is CourseTypeId and CollegeId. When i try to replace this record i get next message:
"SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails (grabmark.course, CONSTRAINT course_course_type_id_course_type_id FOREIGN KEY (course_type_id) REFERENCES course_type (id))"
Anyone can help me please?
Sorry, but i am initiate now in symfony and it's my first contact with an MVC Framework.
Thanks a lot,
Alexandre Sousa
Alexandre, this is more of a database issue than symfony.
When you attempt to update this record, you are changing CourseTypeId and CollegeId with new values and these according to you are foreign keys. Are the values in these fields (CourseTypeId and CollegeId) present in the table where these keys are being referenced from?
For example:
Lets say you are setting CourseTypeId to 15 and CollegeId to 10, then are the values 15 and 10 also present in the database table from where these foreign keys are being referenced? If not, then the Integrity constraint error you are experiencing shows up. Since you are UPDATING and not really INSERTING, then the values 15 and 10 must be present in the table from where the two foreign key columns are referencing.
Does this help?

Cannot delete in EF4

I am trying to delete an "AttendeeEvent" from the database with EF4, however I am getting the following error:-
The operation failed: The relationship could not be changed because one or more of the foreign-key properties is non-nullable. When a change is made to a relationship, the related foreign-key property is set to a null value. If the foreign-key does not support null values, a new relationship must be defined, the foreign-key property must be assigned another non-null value, or the unrelated object must be deleted.
My code is as follows :-
public void UnRegisterCurrentUserForEvent(int eventId)
{
Attendee attendee = GetOrCreateAttendeeForCurrentUser();
AttendeeEvent av = attendee.AttendeeEvents.SingleOrDefault(x => x.EventID == eventId);
if(av != null)
{
attendee.AttendeeEvents.Remove(av);
}
this.ObjectContext.SaveChanges();
}
I tried to change the End 2 On Delete from the properties in the .edmx however when I set to cascade, I am getting an error:-
Error 1 Error 132: cannot have operation specified since its multiplicity is ''. Operations cannot be specified on ends with multiplicity ''
Can you guys help me out
Thanks for your help and time
You are only removing the AttendeeEvent from the collection of attendee events for an Attendee. So suppose you have an attendee A and event AV and you remove AV from A. What should happen inside the database? You haven't actually removed AV. You've only said that A should no longer be related to AV. So inside your database, the foreign key from AV to A is set to NULL, which is not allowed by your database model.
The fix is simple: replace the line where you remove the event from the attendee with the following line:
this.ObjectContext.AttendeeEvents.DeleteObject(av);

Resources