Hello
Below is my model
public class Room
{
public int Id { get; set; }
public string Name { get; set; }
public virtual Floor Floor { get; set; }
public int AcUnitId { get; set; }
public virtual AcUnit AcUnit { get; set; }
}
public class AcUnit
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
public int RoomId { get; set; }
public virtual Room Room { get; set; }
}
Now when i try to assign object
room.AcUnit = room1.Acunit;
I got error "A primary key property that is a part of referential integrity constraint cannot be changed when the dependent object is Unchanged unless it is being set to the association's principal object. The principal object must be tracked and not marked for deletion"
Can anybody help to resolve this?
keyurPosted Feb 9, 2015, 3:18 AM
I already tried to use new object assign each and also using FK this all are work.But I am coufuse as i already have object then why i can not use.
Suraj SahooPosted Feb 9, 2015, 3:16 AM
Suraj SahooPosted Feb 9, 2015, 2:06 AM
If yes, then do the below:
var room = new AcUnit();
room.(All the properties you need for AcUnit , except Id) like
room.Name = room1.Name;
room.OtherProperty = room1.Otherproperty but not the primary key. Else the conflict occurs as you are trying to violate the domians i.e. the uniqueness for the Primary key.
2nd condition:
If primary key is not auto incremented. Assign a unque primary key. But usually this is bad approach. The primary key should be Identity column. you can update the Table at any moment though.
I hope you understand from this the issue.
Accept if this answer helps you anyway.
Thanks
keyurPosted Feb 9, 2015, 1:58 AM
Thanks for reply
room1 is existing object from Room tables.So I fetch exist data and assign room1 acunit to new room.
In which object I have to create Primary key? In room there is already PK is "Id".
Can you tell me more about this?
Keyur
Pranay RanaPosted Feb 9, 2015, 1:57 AM
room.AcUnit = room1.Acunit;
you are actually confusing EF because you are trying to update full entity with its primary key value.
To avoid this you just update property of the object except primary key rather than assigning full object. for this task you may use mapper to map values
or
you can do it delete existing AcUnit object and assign new one that you want.
Suraj SahooPosted Feb 9, 2015, 1:55 AM
This problem is arising, as you are assigning entire object to the same type. That is the primary key conflicts here as that needs to be unique.
You are assigning the same object that to of same type.
Can you please mention what is room1 ??
You first need to make the primary key an identity column(auto-incrementing)
Then assign only the values except Primary key. Then it will create an object of type ACUnit with a unique next primary key.
I hope you understand.
Thanks