So, let’s configure one-to-many relationships using Customer and Order entities
Customer.cs
- public class Customer
- {
- public int CustomerId
- {
- get;
- set;
- }
- public string CustomerName
- {
- get;
- set;
- }
- public string CustomerEmail
- {
- get;
- set;
- }
- public int OrderId
- {
- get;
- set;
- }
- public virtual Order Order
- {
- get;
- set;
- }
- public Customer()
- {
- }
- }
Order.cs
- public class Order
- {
- public int OrderId
- {
- get;
- set;
- }
- public DateTime Date
- {
- get;
- set;
- }
- public int price
- {
- get;
- set;
- }
- public virtual ICollection < Customer > Customer
- {
- get;
- set;
- }
- public Order()
- {
- }
- }
Now, you can configure one-to-many relationships as shown below:
- protected override void OnModelCreating(DbModelBuildermodelBuilder)
- {
-
- modelBuilder.Entity < Customer > ().HasRequired < Order > (o => o.Order)
- .WithMany(c => c.Customer);
- }
Now, I would like to add, suppose if customer and order entities don’t follow code first conventions for foreign key. For example, the customer class includes different foreign key (ex: ordId) for order entity. In this case you will proceed as follows:
- protected override void OnModelCreating(DbModelBuildermodelBuilder)
- {
-
- modelBuilder.Entity < Customer > ()
- .HasRequired < Order > (o => o.Order)
- .WithMany(c => c.Customer)
- .HasForeignKey(o => o.OrdId);
- }
Before finishing, I want share with yo, how to make Nullable foreign key for one-to-many relationships. For doing this, you should write the following code as shown below:
- protected override void OnModelCreating(DbModelBuildermodelBuilder)
- {
- modelBuilder.Entity < Customer > ()
- .HasOptional < Order > (o => o.Order)
- .WithMany(c => c.Customer);
- }
In the next blog, we learn how to configure many-to-many relationships using Fluent API.