Insert foreign key reference in entity frameowrk 3.5 - c#

I have 3 tables
a. Employee (EmpID (pk), EmpName)
b. Department (DepID (pk), DepName)
c. EmployeeDepartmentMapping (ID (pk), EmpID(fk), DepID(fk))
When I am inserting new employee, I want to insert correspoding Emp-Dep mappings in the EmployeeDepartmentMapping table using entity framework 3.5. Can any body help/tell me how to insert many-many relationships using entity framework in database?
Thanks,
Ashwani

Employee emp = new Employee();
EmployeeDepartmentMapping edm = new EmployeeDepartmentMapping();
edm.Emp = emp;
if u know the dept id.
then
edm.Dept = _ent.Department.where(i => i.deptId == dept_id).first();
_ent.AddToEmplyee(emp);
_ent.AddToEmployeeDepartmentMapping(edm);

emp.<RolesEmpMapTable>Refernce.Load();
emp.<RolesEmpMapTable>.Role = _ent.Roles.where(i=>i.roleId == role_id).first();

Related

How to use EntityState for related tables (FK) in Entity Framework 6?

Consider the following table
Table 1 : Employee
Id
Name
Email
Table 2 : Vehicle
Id
EmployeeId
VehicleId
An Employee can have multiple Vehicle.
Now based on some condition I want to not allow user to update the employee table and vehicle table.
So for this, for the employee table I use
var emp = appContext.Employee.Find(empId);
// some update code goes here
if(someCondition(userId))
appContext.Entry(emp).State = EntityState.Unchanged;
This works fine.
Now how do I do the same for the related Vehicle table ?
Update 1
I tried this and it did not work
appContext.Entry(emp).Collection(r => r.Vehicle).EntityEntry.State = EntityState.Unchanged;

Lambda vs Query Expression Entity framework / Foreign Key relationship

In brief: is there any difference between fetching records using lambda expression vs using query expression?
In below example:
I fetched one employee record
Modified his salary Without saving
changes to context I fetch same record with Salary table included
Why are the results different when doing query 2 vs query 3?
var empdId = Guid.Parse("C8475622-09A9-4284-80D4-AAXXK");
//City for this employee was Washington in database
var emp = ctx.Employee
.FirstOrDefault(emp => emp.ID == empId);
emp.City = "New York"; //Modified the entity
//Lambda version
//Fetched again including foreign key relation Salary
var employeeCity = ctx.Employee.Include("Salary")
.FirstOrDefault(emp => emp.ID == empdId).City;
//New York
var cityfetchedAgain = from e in ctx.Employee
join sal in ctx.Salary on e.ID equals sal.EmployeeId
where e.ID == empdId
select e.City;
var city = cityfetchedAgain.FirstOrDefault();
//Washington
EDIT:
I will re-phrase my question: Include version of query returns the changed property, even if the changes are not committed to database. However LINQ Join is not aware of changes in the context (City property here). Records were fetched from database.
I have explicit foreign key configured between these tables. Should I
always prefer Include?

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

Table with 2 foreign keys entity framework

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();

Categories