C# Corner
Tech
News
Videos
Forums
Trainings
Books
Events
More
Interviews
Jobs
Live
Learn
Career
Members
Blogs
Challenges
Certifications
Bounties
Contribute
Article
Blog
Video
Ebook
Interview Question
Collapse
Feed
Dashboard
Wallet
Learn
Achievements
Network
Refer
Rewards
SharpGPT
Premium
Contribute
Article
Blog
Video
Ebook
Interview Question
Register
Login
Configure One-to-Many Relationships Using Fluent API
WhatsApp
El Mahdi Archane
9y
5.1
k
0
0
25
Blog
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)
{
// one-to-many
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)
{
//one-to-many
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.
People also reading
Membership not found