The first thing we need to do is create the models for the objects that we need.
Here are the steps to create models for the Northwind Cafe entities:
1. Create a "Models" folder, and create four files
- Product.cs
- Order.cs
- Category.cs
- OrderDetail.cs
2. In the Product.cs file type in the following code
using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace NorthwindCafe.Web.Models { public class Product { public int Id { get; set; } public string Name { get; set; } public string Description { get; set; } public decimal Price { get; set; } public virtual Category Category { get; set; } } }
The code above gives the Product class properties Id, Name, Description, and Price. Those maps to what will become the columns in the database.
The line
public virtual Category Category { get; set; }
Tells Entity Framework that there is a foreign key constraint between the Product table and the Category table. Basically there's a one-to-many relationship between the Product and the Category table. Meaning there could be many products to one category.
3. In the Category.cs file type in the following code
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace NorthwindCafe.Web.Models { public class Category { public int Id { get; set; } public string Name { get; set; } public string Description { get; set; } public virtual ICollection<Product> Products { get; set; } } }
Since a category can have more one product in our database, there's a navigation property in Category entity. This means that the category entity can navigate (access, query) all the products that belongs to it. That's the power of entities, you don't have to do a database join to get products that belongs to a particular category.
4. In the Order.cs file type in the following code
using System.Linq; using System.Threading.Tasks; namespace NorthwindCafe.Web.Models { public class Order { public int Id { get; set; } public DateTime OrderDate { get; set; } public virtual ICollection<OrderDetail> OrderDetails { get; set; } } }
5. In the OrderDetails.cs file type in the following code
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace NorthwindCafe.Web.Models { public class OrderDetail { public int Id { get; set; } public int Quantity { get; set; } public decimal Price { get; set; } public virtual Product Product { get; set; } public virtual Order Order { get; set; } } }
The code above has the same concept, the OrderDetails entity has a foreign constraint to the Product and Order table/entity, and the Order table/entity can navigate to the OrderDetails table/entity.
Mua vé tại đại lý vé máy bay Aivivu, tham khảo
ReplyDeletegiá vé máy bay đi Mỹ khứ hồi
đã có chuyến bay từ mỹ về việt nam chưa
lich bay tu duc ve viet nam
khi nào có chuyến bay từ nga về việt nam
chuyến bay từ anh về việt nam
bay từ pháp về việt nam mấy tiếng
chuyến bay chuyên gia trung quốc