how can i save the primary key of a entity in another entity when entity framework is saving - entity-framework

so I have this problem I am doing an import and I need when save the first table that primary key of the first table save too in another table that is not a foreing key , is a way that EF do that? Iam using EF5
is something like this, note that entity1.id is autoIncrement
foreach (var entity1 in Entities1)
{
DbContext.Entity1.Add(entity1);
var entity2 = new Entity2();
entity2.Entity1Id = entity1.id;
DbContext.Entity2.Add(entity2);
}
DbContext.SaveChanges();

Id is not generated until SaveChanges is called. So for this code to work, you have to rewrite it down like this:
DbContext.Entity1.Add(entity1);
DbContext.SaveChanges();
var entity2 = new Entity2();
entity2.Entity1Id = entity1.id;
DbContext.Entity2.Add(entity2);
DbContext.SaveChanges();

Related

Get Record ID in Entity Framework 5 after insert

I realize this must be a relatively simple thing to do, but I'm not getting what I'm looking for with Google.
I need to get the record ID of the record I just saved using the Entity Framework. With SQL queries we used "Select ##IDENTITY as 'Identity';"
If anyone can help it would be greatly appreciated.
The default behavior of Entity Framework is it sets identity fields on entities from the database right after SaveChanges is called.
In the following sample code, before SaveChanges is called, my employee has a default ID of 0. After SaveChanges my employee has a generated ID of 1.
using (TestDbEntities context = new TestDbEntities())
{
Employee e = new Employee ();
e.FirstName = "John";
e.LastName = "Doe";
context.Employee.Add(e);
context.SaveChanges();
Console.WriteLine("Generated ID: {0}", e.ID);
Console.ReadKey();
}

Many-to-Many insert failing - Entity Framework 4.1 DbContext

I am using DB first method, EF 4.1 with DbContext POCO code gen.
My database has a many-to-many relationship as shown below:
Employee
EmployeeId
EmployeeName
Account
AccountId
AccountName
EmployeeAccount
EmployeeId
AccountId
The problem occurs when I am trying to insert a new Employee, and assign them a pre existing account, so I am basically doing this as below:
Employee emp = new Employee();
emp.EmployeeName = "Test";
emp.Accounts.Add(MethodThatLooksUpAccountByName("SomeAccountName"));
context.Employees.Add(emp);
context.SaveChanges();
The SQL this is executing (incorrectly), is attempting to INSERT a new [Account] record, and this is failing on a constraint violation. Of course, it should not INSERT a new [Account] record, it should only insert a new [EmployeeAccount] record, after inserting the [Employee].
Any advice? Thanks.
MethodThatLooksUpAccountByName does this method return an attached or detached object? In any case, you may try to attach the object it returns to the context.
Employee emp = new Employee();
emp.EmployeeName = "Test";
var acc = MethodThatLooksUpAccountByName("SomeAccountName");
context.Attach(acc); //I don't remember if it's attach or attachobject, but intellisense should help you there.
emp.Accounts.Add(acc);
context.Employees.Add(emp);
context.SaveChanges();

Entity Framework Insert, Update, Delete During Same Transaction

I have a problem, I have a wizard that can update data AND insert data. So, if I have an existing list of team members, I can update their roles but If necessary, I can also add/insert a person to this team. So I can update roles and insert a new team member into the same table all during the same transaction. Data can be updated to and inserted to table teamMembers.
When I try to add a new teamMember, I also have an existing member where I simply want to update his role.
Both changes happen to the same table called TeamMember. When I debug the context, everything looks good. it shows that there are two changes that will occur for the TeamMember table. One transaction is the update and the other transaction is the insert. When I perform an update using:
var teamMember = new TeamMember
{
Name = user.FullName,
UserProfileId = user.UserProfileId,
RoleId = user.RoleId
};
TeamMemberList.Add(teamMember);
project.TeamMembers = TeamMemberList;
//And then call
this.Context.Projects.Attach(project);
this.Context.Entry(project).State = System.Data.EntityState.Modified;
it updates but the record that needs to be inserted fails.
HOW CAN I DO BOTH AN INSERT AND UPDATE TO THE SAME TABLE DURING THE SAME TRANSACTION?
CURRENT ERROR IS:
The changes to the database were committed successfully, but an error occurred while updating the object context. The ObjectContext might be in an inconsistent state. Inner exception message: A referential integrity constraint violation occurred: The property values that define the referential constraints are not consistent between principal and dependent objects in the relationship.
I think you need to add the TeamMember entity to the context's global list. Something like:
var teamMember = new TeamMember()
{
Name = user.FullName,
UserProfileId = user.UserProfileId,
RoleId = user.RoleId
}
project.TeamMembers.Add( teamMember );
this.Context.TeamMembers.Add( teamMember );
this.Context.SaveChanges();
How about loading the existing project entity first and then adding members.
var project = this.Context.Project.Where(p => p.ID = "bar").Include("TeamMembers").FirstOrDefault();
var teamMember= new TeamMember
{
Name = user.FullName,
UserProfileId = user.UserProfileId,
RoleId = user.RoleId
};
project.TeamMembers.Add(teamMember);
this.Context.SaveChanges()

Entity Framework - How to Set Association Value?

Let's say I have a Person class and an Order class, with foreign keys in the DB. The EF model will mark Person with a List of Orders and Order with a Person instance.
If I want to set the Person for the Order, do I really have to do it with an instance of Person?
Is there not a slimmed down way to do so, say with just a PersonID ?
To assign Person entity to a Order without loading Person entity, you have to do something like this:
var db = new OneToManyEntities();
var Order = new Order { OrderId = 100, OrderName = "Order name" };
Order. PersonReference.EntityKey = new EntityKey("OneToManyEntities.Person ","PersonID",10);
db.AddToOrders(Order);
db.SaveChanges();
Puzzled's answer is correct for EF v1. It's a pain. If you don't mind the extra query, you can set the property succinctly:
int id = 1;
Order.Person = context.Persons.Where(x => x.PersonID == id).FirstOrDefault();
Entity Framework v4 will have "FK Associations", which is a fancy term for directly-settable foreign keys.

Entity Frmwk pb: search for 'added' entities in current context

I'm using guids as PK for my entities.
As EF doesn't support the newid() SQL statement, I force a Guid.NewGuid() in my creation methods.
Here is my problem :
I've a table with a clustered unique constraint (2 strings, not PK).
I'm running some code in the same EF context which perfoms operations and adds/links entities, etc.
Is it possible to search for an entity in 'Added' state in my context ? ; that is to say which is in my context, but not yet inserted in my DB.
To avoid the raising of the SQL unique constraint, I have to know if the entity is already 'queued' in the context, and to re-use it instead of creating a new Guid (... and a different entity! :( )
this post saved me :) :
Link
var stateEntries = context.ObjectStateManager.GetObjectStateEntries(EntityState.Added | EtityState.Modified | EntityState.Unchanged);
var roleEntityEntries = stateEntries.Select(s => s.Entity).OfType<Role>();
roleEntity = roleEntityEntries.FirstOrDefault(r => r.RoleName.Trim().ToLower() == roleName.Trim().ToLower());
if (roleEntity == null)
{
return new Role { RoleName = roleName };
}