Why is this Exception?- The relationship between the two objects cannot be defined because they are attached to different ObjectContext objects - entity-framework

I m getting this Exception-"The relationship between the two objects cannot be defined because they are attached to different ObjectContext objects."
I ve user table and country table. The countryid is referred in user table.
I am getting the above Exception when I am trying to add entry in user table.
This is my code-
using (MyContext _db = new MyContext ())
{
User user = User .CreateUser(0, Name, address, city, 0, 0, email, zip);
Country country = _db.Country.Where("it.Id=#Id", new ObjectParameter("Id",countryId)).First();
user.Country = country;
State state = _db.State.Where("it.Id=#Id", new ObjectParameter("Id", stateId)).First();
user.State = state;
_db.AddToUser(user );//Here I am getting that Exception
_db.SaveChanges();
}

Try adding the user first, then adding the relationships.
See http://www.code-magazine.com/article.aspx?quickid=0907071&page=4
Or, don't use User.CreateUser where you are explicitly setting an Id = 0, instead use User user = new User() {Name = Name, Address = ...}
BTW, with Entity Framework 4 you can set the foreign key IDs directly removing the need to load the related object if you know its ID.

Related

Why can't EF handle two properties with same foreign key, but separate references/instances?

Apparently, EF6 doesn't like objects that have multiple foreign key properties that use the same key value, but do not share the same reference. For example:
var user1 = new AppUser { Id = 1 };
var user2 = new AppUser { Id = 1 };
var address = new Address
{
CreatedBy = user1, //different reference
ModifiedBy = user2 //different reference
};
When I attempt to insert this record, EF throws this exception:
Saving or accepting changes failed because more than one entity of type
'AppUser' have the same primary key value. [blah blah blah]
I've discovered that doing this resolves the issue:
var user1 = new AppUser { Id = 1 };
var user2 = user1; //same reference
I could write some helper code to normalize the references, but I'd rather EF just know they're the same object based on the ID alone.
As for why EF does this, one explanation could be that its trying to avoid doing multipe CRUD operations on the same object since separate instances of the same entity could contain different data. I'd like to be able to tell EF not to worry about that.
Update
So it's as I suspected per my last paragraph above. In absense of a means to tell EF not to do CRUD on either instance, I will just do this for now:
if (address.ModifiedBy.Id == address.CreatedBy.Id)
{
address.ModifiedBy = address.CreatedBy;
}
Works well enough so long as I am not trying to do CRUD on either.
Update2
I've previously resorted to doing this to prevent EF from validating otherwise-required null properties when all I need is the child entity's ID. However, it doesn't keep EF from going into a tizzy over separate instances with the same ID. If it's not going to do CRUD on either AppUser object, why does it care if the instances are different?
foreach (var o in new object[] { address.ModifiedBy, address.CreatedBy })
{
db.Entry(o).State = EntityState.Unchanged;
}
If you get AppUser from context, then you will not need to do anything, because Entity Framework will track entities:
var user1 = context.AppUsers.Find(1);
var user2 = context.AppUsers.Find(1);
var address = new Address
{
CreatedBy = user1, //different reference
ModifiedBy = user2 //different reference
};
Now, they both will point to same objects and will not cause to conflict.
You can add two extra properties to have the Id for the main objects which is the AppUser, then you can use only one AppUser object and reference it for both the created and modified by properties.
CreatedById = user1.Id,
ModifiedById = user1.Id
Otherwise, your code will end up by saving two instances of AppUser with the same primary key.
Another approach is to set both the foreign key properties to only one AppUserobject
The explanation is that EF's change tracker is an identity map. I.e. a record in the database is mapped to one, and only one, CLR object.
This can be demonstrated easily by trying to attach two objects with the same key:
context.AppUsers.Attach(new AppUser { Id = 1 });
context.AppUsers.Attach(new AppUser { Id = 1 });
The second line will throw an exception:
Attaching an entity of type 'AppUser' failed because another entity of the same type already has the same primary key value.
This also happens if you assign
CreatedBy = user1, //different reference
ModifiedBy = user2 //different reference
Somewhere in the process, user1 and user2 must be attached to the context, giving rise to the exception you get.
Apparently, you have a function that receives two Id values that can be different or identical. Admittedly, it would be very convenient if you could simply create two AppUser instances from these Ids, not having to worry about identical keys. Unfortunately, your solution ...
if (address.ModifiedBy.Id == address.CreatedBy.Id)
... is necessary. Solid enough, though.

JPA recursive entity StackOverflowError

I have a User entity generated in Netbeans from an existing database table. The table has a column lastUpdatedByUser that is a User entity. Most of the tables in this database have a lastUpdatedByUser column and queries against those entities correctly return a user object as part of the result.
Ex. Retrieve FROM ProductionTable WHERE date = 'someDate' has a lastUpdatedByUser object that shows who last updated the table row and the rest of their user attributes.
If the productionTable data is edited in the web-app and submitted I need to update the lastUpdatedByUser column.
Users userUpdating = usersService.selectUserEntityByUserId(userId);
Users userEntity = usersFacade.findSingleWithNamedQuery("Users.findByUserId", parameters);
SELECT u FROM Users u WHERE u.userId = :userId
returns a User object that contains a lastUpdatedByUser that is a User object that contains a lastUpdatedByUser that is a User object that contains a lastUpdatedByUser object.... (I have no clue how many there are, and twenty rows of these adds up)
After I persist this
productionEntity.setLastUpdatedByUser(userUpdating);
I get Json StackOverflowError in the next request for the updated entity
gson.toJson(updatedProductionEntity)
The Users entity definition:
#OneToMany(mappedBy = "lastUpdatedByUser")
private Collection<Users> usersCollection;
#JoinColumn(name = "LastUpdatedByUser", referencedColumnName = "UserId")
#ManyToOne
private Users lastUpdatedByUser;
#OneToMany(mappedBy = "lastUpdatedByUser")
private Collection<Production> productionCollection;
How can edit that such that I continue to get a user object as part of other entities like Production, but only a single lastUpdatedByUser object for a User entity?
Thanks for any insight.
I'm guessing this is my issue:
#JoinColumn(name = "LastUpdatedByUser", referencedColumnName = "UserId")
as I found a FK in the Users table to its own UserId
Love refactoring
================================
Drop that FK from the Users table and regenerate the entity in Netbeans and I get
private Integer lastUpdatedByUser;
like it should be
instead of
private Users lastUpdatedByUser;
Now I get to edit all the entities that have valid FKs into the Users table and code and...
Thanks for listening.

Inserting record in Entity Framework without Foreign Key References

Please see below my ERD. Both Company and Contact can have ContactDetails and be Users at the same time. As such I haven't explicitly defined foreign key relationships with these tables. I user UserType (int) to determine whether it is Company or Contact and then store the relevant ID in the EntityId field.
Here is the code snippet I use to insert a new Company in the database.
public ActionResult Create(ProjectUser user)
{
if (ModelState.IsValid)
{
if (user.UserType == (int)PC.Utils.Enums.UserType.Company)
{
Company company = user.GetCompany(); // Get Company UI values from View Model
ContactDetail detail = user.GetContactDetail(); // Get Contact UI values from View Model
detail.UserType = (int)UserType.Company; // bind contact Type to Company Type
detail.EntityId = company.Id;
User login = user.GetLoginDetails(); // Get User UI values from View Model
login.UserType = (int)UserType.Company; // bind User Login to Company
login.EntityId = company.Id;
login.Password = PC.Utils.Security.GetMD5Hash(login.Password); // encrypt the password
db.Companies.Add(company);
db.ContactDetails.Add(detail);
db.Users.Add(login);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(user);
}
However, when I check the database the EntityId in both Users and ContactDetails table is 0, as EF did not determine the correct ID in the transaction. Is there something I am missing, or is there a nicer way to achieve this?

EntityReference has an EntityKey property value that does not match the EntityKey for this object

I want to add the user in Users table with Entity Framework.
I added all the references viz.
this.UserRolesReference.EntityKey = new System.Data.EntityKey("KEntities.UserRoles", "UserRoles", roleID);
this.OfficeMasterReference.EntityKey = new System.Data.EntityKey("KEntities.OfficeMaster", "SROCode", SROCode);
this.UserDesignationsReference.EntityKey = new System.Data.EntityKey("KEntities.UserDesignations", "UserDesignations", designationId);
When I do this
context.AddObject(this.GetType().Name.ToString(), this);[ this is object of Users]
it gives me an error
The object could not be added or attached because its EntityReference has an EntityKey property value that does not match the EntityKey for this object.
The Users table has only relationship with UserRoles , UserDesignations and OfficeMaster
Still in the KModel.edmx file under Users table in the Navigation Properties it shows CustomPermissions, UserLog
CustomPermissions and UserLog have an association with Users but I am not inserting any values into them.
Thank you in advance
In Entity Framework, you are not supposed to change or set RoleID manually, instead you must set the navigation property and RoleID will be correctly updated.
Role adminRole = GetTheAdminRole(); // get instance of Role
User newUser =new User();
context.Users.Add(newUser);
newUser.Role = adminRole;
context.SaveChanges();

Many-to-Many Inserts with Entity Framework

Say I have two entities with about 20 properties per entity and a Many-to-Many relationship like so:
User (Id int,Name string, .......)
Issue (Id int,Name string, .......)
IssueAssignment (UserId,RoleId)
I want to create a new Issue and assign it to a number of existing Users. If I have code like so:
foreach(var userId in existingUserIds)
{
int id = userId
var user = _db.Users.First(r => r.Id == id);
issue.AssignedUsers.add(user);
}
_db.Users.AddObject(user);
_db.SaveChanges();
I noticed it seems terrribly inefficient when I run it against my SQL Database. If I look at
the SQL Profiler it's doing the following:
SELECT TOP(1) * FROM User WHERE UserId = userId
SELECT * FROM IssueAssignment ON User.Id = userId
INSERT INTO User ....
INSERT INTO IssueAssignment
My questions are:
(a) why do (1) and (2) have to happen at all?
(b) Both (1) and (2) bring back all fields do I need to do a object projection to limit the
fields, seems like unnecessary work too.
Thanks for the help
I have some possible clues for you:
This is how EF behaves. _db.Users is actaully a query and calling First on the query means executing the query in database.
I guess you are using EFv4 with T4 template and lazy loading is turned on. T4 templates create 'clever' objects which are able to fixup their navigation properties so once you add a User to an Issue it internally triggers fixup and tries to add the Issue to the User as well. This in turns triggers lazy loading of all issues related to the user.
So the trick is using dummy objects instead of real user. You know the id and you only want to create realtion between new issue and existing user. Try this (works with EFv4+ and POCOs):
foreach(var userId in existingUserIds)
{
var user = new User { Id = userId };
var _db.Users.Attach(user); // User with this Id mustn't be already loaded
issue.AssignedUsers.Add(user);
}
context.Issues.AddObject(issue);
context.SaveChanges();