Table with 2 foreign keys entity framework - c#

I have a table which consists of 2 foreign keys. And those are only elements of the table. The table is meant to create association between 2 other tables. For example: The table is Users_Products, and the only 2 columns are UserId and ProductID, both foreign keys. When I generated the EF object from database it didn't create Users_Products object, it only automatically created navigation properties. Now how can I insert data in my Users_Products table using EF?

You can get some user object and add product into its navigation property.
User user = context.Users.Where(u => u.Id == 1);
Product product = context.Products.Where(p => p.Id == 1);
user.Products.Add(product);
context.SaveChanges();

For code examples that show how to work with many-to-many relationships in EF see the Working with Many-to-Many Relationships section in
The Entity Framework 4.0 and ASP.NET – Getting Started Part 5.
That is EF 4.0 / Database First; for an example using the DbContext API, see Adding Course Assignments to the Instructor Edit Page in Updating Related Data with the Entity Framework in an ASP.NET MVC Application (6 of 10).

using ( var ctx = new ...)
{
var user = new User();
var product = new Product();
user.Products.Add(product);
ctx.Users.AddObject(user);
ctx.SaveChanges();
}

If you want to create relation (insert record to User_Products table) you just need to use navigation property either on User or Product:
user.Products.Add(product);
or
product.Users.Add(user);
That means you must have navigation property on at least one side to be able to create the relation. If you have loaded entities from the current contest you can use the approach described by #Pavel.
If you don't have loaded entities or if you don't want to do two queries to the database just to make a relation you can use this workaround:
// Make dummy objects for records existing in your database
var user = new User() { Id = 1 };
var product = new Product() { Id = 1 };
// Ensure that your context knows instances and does not track them as new or modified
context.Users.Attach(user);
context.Products.Attach(product);
// Again make relation and save changes
user.Products.Add(product);
ctx.SaveChanges();

Related

Entity Framework-Saving models with related tables

So my question basically has to do with nested models or associated tables (not sure the correct term).
Specifically when TableA has an ICollection of TableB objects and TableB has an ICollection of TableA, how do I then save off my entire TableA model along with it's assocaited Table2 items.
For example:
User table with: string name, string address, ICollection < Orders >
Orders table with: OrderID, Total, ShipDate, ICollection < User >
So I have a User instance (UserA) which has the name and address set along with a collection of orders (Let's say Bob Dole, 1234 Main st, [567, $12.34, Oct 1; 999, $27.89, Nov 5;]).
How do I trigger the save method to save both Orders & the User?
My expectation would be "db.User.add(UserA); + db.SaveChanges();". I would expect this to save the User and upon seeing the Orders collection, save those as well.
However, previous developers did this:
User userB = db.User.Add(new User(userA.Name, userB.address)); //Why do we have to create a 2nd instance of a User object, that will hold the same information as userA?
foreach(Order order in userA.orders)
{
Order NewOrder = db.Orders.Add(order); //This now updates the Orders table with new info, which will be saved by 'db.SaveChanges()'
NewOrder.User.Add(userB); //How does this update the value in the Orders table with the userID? Isn't this updating the object about to go out of scope?
}
db.SaveChanges()
The only thing we can think, is the way they did it userB get's 'ID' assigned from the .Add command. But couldn't you simply say "userA = db.Users.Add(userA)" in order to update the instance with the ID provided upon database insert?
First of all, I think, you've got to change your schema.
There will be one-to-many relationship between User and Orders. One user can have multiple orders but one order can not belong to multiple users. i.e. Only Order table would have UserId.
Update
Further, No need to add Orders data separately. As there would available collection type in the User table's entity.
You need to just assign values to the User table's entity along with Orders field and do insert it only once.
The code would be somehow as below:
var userData = user;
var orderData = orderCollection;
userData will be single record and orderData could be multiple.
Now assign that data to User data model:
var userAndOrder = new User
{
Name = user.Name,
Address = user.Address,
Orders = orderCollection.Select(o => new Order
{
//assign order fields here
}).ToList();
};
Then save this data. It will save Orders data itself in the Order table against the UserId.
db.Add(userAndOrder);
db.SaveChanges();

Upgraded to Entity Framework 6 Related entities not being inserted

I upgraded From EF 4 to EF6 in my solution. Now my related entities are not getting inserted. How do I add records to the entity with foreign key relationship from the original enity
var _bp = new BP(); //BP is an entity
workflowList.ForEach(wf =>
{
var wflow = new Workflow
{
currentstep = CustomConvert.ToIntNullable(wf.currentstep),
desc = wf.desc,
name = wf.name,
wfId = wf.id,
BP = _bp,
IsActive = true
};
});
db.BP.AddObject(_bp);
db.SaveChanges();
The code above would add a record in BP table and add multiple records in the workflow table in EF 4 but in EF 6 it does not add any record to the Worflow table. How do I accomplish the same in EF6

How do I insert a record with the key of the previous record in one call?

In my database, I have a table called Department that columns named DepartmentID (PK) and SubdepartmentOfID (FK). SubdepartmentOfID is constrained as a FK to DepartmentID in order to basically create a hierarchical type relationship.
What I'm trying to do in Entity Framework 6 is to create a default subdepartment that has the same name as the department, but in order to do so, I need to be able to set the SubdepartmentOfID before inserting it though my context, right? Currently, I'm using this logic:
Create the entity, insert it, save it (this ends up populating the DepartmentID key in the entity).
Create another entity for the subdepartment and set its SubdepartmentOfID property equal to that of the previously saved entity, save it
I feel like this could be done in one call. Can it?
This answer assumes the following:
You're using database first (using the designer) as opposed to code first
You have a table named Department with the following columns
DepartmentID
SubDepartmentID
DepartmentName
I think you can do this.
var department = new Department
{
DepartmentName = "D1"
};
var subDepartment = new Department
{
DepartmentName = "D1"
};
department.Department = subDepartment;
context.Departments.Add(department);
context.SaveChanges();
Entity framework will now take care of the autogenerated IDs and associate the sub department to the department.

Multiple added entities may have the same primary key in Entity Framework

I am working in a project using EF 4.0.
The Employee table has a column ReferEmployeeID which contains the employee id of the employee that is referring a new employee in the system. So Employee is a self-referencing table.
Now in the case of an employee who is not added to the system is about to add and he also refers another employee in the system, the row should be added altogether.
ActualEmployee save not called yet and then ReferEmployee.Employee = ActualEmployee
I understand the issue is that both the employees actual and refer has Employee ID set to 0, but how to come around this problem.
Assuming that the EmployeeID in your database table is defined as INT IDENTITY, then you could do this:
// create two new employees - one refers to the other
Employee john = new Employee { EmployeeID = -1, EmpName = "John" };
Employee peter = new Employee { EmployeeID = -2, EmpName = "Peter", ReferEmployeeID = -1 };
// add them to the EF model
ctx.AddToEmployees(john);
ctx.AddToEmployees(peter);
// save changes
ctx.SaveChanges();
So basically, define your new employees with "dummy" EmployeeID values and establish the link (Peter references John here, by means of its "dummy" ID).
When saving this into SQL Server, the Entity Framework will handle the process of getting the real EmployeeID values (which SQL Server hands out when inserting the row) and EF will maintain that link between the two employees.

C# - Entity Framework inserting

I have two tables Category and Product and I would like to insert products into categories. The table relation between these tables is one to zeor or one.
Category table:
CID : integer,
CategoryName : varchar,
Product table:
CID: integer, // foreign key to category table.
ProductName: varchar,
UnitsInstock: integer,
How can I write a simple query for inserting a product into the ProductTable? How do I handle the foriegn key situation? If the categoryid does not exists then the product should not be inserted.
I would realy appreciate any kinds of help.
One approach could be this one:
int categoryIdOfNewProduct = 123;
using (var context = new MyContext())
{
bool categoryExists = context.Categories
.Any(c => c.Id == categoryIdOfNewProduct);
if (categoryExists)
{
var newProduct = new Product
{
Name = "New Product",
CategoryId = categoryIdOfNewProduct,
// other properties
};
context.Products.Add(newProduct); // EF 4.1
context.SaveChanges();
}
else
{
//Perhaps some message to user that category doesn't exist? Or Log entry?
}
}
It assumes that you have a foreign key property CategoryId on your Product entity. If you don't have one please specify more details.
Normally a category to product would be many to one, but I would suggest studying the basics of Linq to Sql first:
http://msdn.microsoft.com/en-us/library/bb425822.aspx
Linq to Sql 101
Learn the Entity Framework

Categories