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
Related
Doing a shop project. Upon checkout, I create a list of all added product from cart and put it inside Order.Products(M-M relationship):
List<Product> productList = Cart.Select(item => db.Products.SingleOrDefault(x => x.Id == item)).ToList();
var addOrder = new Order
{
Id = Guid.NewGuid(),
UserId = userId,
OrderDate = DateTime.Now,
Products = productList
};
db.Orders.Add(addOrder);
db.SaveChanges();
I debugged my code to make sure the productsList had the right amount.
But after I added it, I only had one of each added products were added in my db. For e.g. if I have 3x cars, 4x books and 2x boat, then I just get one of each into M-M table, meaning total 3 products, even though I had total 9 in productList.
This is how I set up my m-m relationship.
create table Product_Order (
ProductId uniqueidentifier foreign key references [Product](ID) not null,
OrderId uniqueidentifier foreign key references [Order](Id) not null
)
Btw, is it possible to add additional column into Product_Order so called AmountProduct, and set amount value instead making many rows of same products/order? If possible, how do I set amount value inside var addOrder = new Order{? That way would probably be much more effective.
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;
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.
I am trying to learn linq to sql/objects as quick as possible. I have a database with a Category table, and a sub_category table. A Category can have many Sub Categories. As a lesson, I am getting a list of categories. User enters the primary key from a displayed category, and then I wnt to display all sub categories.
Displaying the categories was easy... But Entity Framework has removed the foreign keys from Sub Category! I expect to see a category Id in the sub category table (As there is in the SQL server database model).
Instead, I have some CategoryReference property... How do I manage this?
static void Main(string[] args)
{
BudgieMoneyEntities db = new BudgieMoneyEntities();
var categories = (
from category in db.categories
select category).ToList();
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Categories:");
Console.ForegroundColor = ConsoleColor.White;
foreach (category cat in categories)
{
Console.WriteLine(string.Format("{0:00} {1}", cat.category_id,
cat.description));
}
int categoryId = WaitForKey();
var subcategories = (
from subcategory in db.sub_category
where subcategory ?? ?
select subcategory).ToList();
}
The ?? is where I have got stuck... How do I do this where clause?
Try this:
var subcategories = (
from subcategory in db.sub_category
where subcategory.category.category_id == categoryId
select subcategory).ToList();
The names of the properties category and category_id can be different. You can look at your model in the EF designer what the actual names are. If the category property is missing, make sure you've got a foreign key relationship between the categories table and the subcategories table.
You also want to change the default names of entities and properies in the EF designer. For instance, use plural names for sub collections. For instance, use db.SubCategories instead of db.sub_category. That makes it much more readable.
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();