One-to-zero or one relationship using Fluent API
Let’s configure one-to-zero or one relationship using Customer and Customer Address entities.
Customer.cs
- public class Customer
- {
- publicintCustomerId
- {
- get;
- set;
- }
- public string CustomerName
- {
- get;
- set;
- }
- public string CustomerEmail
- {
- get;
- set;
- }
- public CustomerAddressCustomerAddr
- {
- get;
- set;
- }
- publicCustomer()
- {
- }
- }
CustomerAddress.cs
- public class CustomerAddress
- {
- public int CustomerAddressId
- {
- get;
- set;
- }
- public string Address
- {
- get;
- set;
- }
- public string City
- {
- get;
- set;
- }
- public CustomerCustomer
- {
- get;
- set;
- }
- public CustomerAddress()
- {
- }
- }
Now, we can pass to configure one to one or zero relationship using code as shown below:
- protected override void OnModelCreating(DbModelBuildermodelBuilder)
- {
-
- modelBuilder.Entity < Customer > ()
- .HasOptional(c => c.CustomerAddr)
- .WithRequired(Ad => Ad.Customer);
- }
- HasOptional (c=>c.CustomerAddr) indicates that Address is optional for customer entity.
- WithRequired (Ad=>Ad.Customer) indicates that Customer property is required for Customer Address entity then you can understand that you cannot save Customer Address without Customer.
Note
One-to-one is not possible in MS SQL Server. EF creates one-to-zero or one relationship on entities not in database.
At this level, I would like to share with you the following question:
If CustomerAddressId does not follow primary key convention (className<Id>), how can we do to handle this problem?
Now, let’s consider the following Customer & CustomerAddress entities.
- public class Customer
- {
- public int CustomerID
- {
- get;
- set;
- }
- public string CustomerName
- {
- get;
- set;
- }
- public string CustomerEmail
- {
- get;
- set;
- }
- public CustomerAddressCustomerAddr
- {
- get;
- set;
- }
- public Customer()
- {
- }
- }
- public class CustomerAddress
- {
- public int Id
- {
- get;
- set;
- }
- public string Address
- {
- get;
- set;
- }
- public string City
- {
- get;
- set;
- }
- public CustomerCustomer
- {
- get;
- set;
- }
- public CustomerAddress()
- {
- }
- }
So, to overcome this problem, we need to add line which specifies Id property is considered as primary key.
- protected override void OnModelCreating(DbModelBuildermodelBuilder)
- {
-
- modelBuilder.Entity < CustomerAddress > ().HasKey(CA => CA.Id);
- modelBuilder.Entity < Customer > ()
- .HasOptional(c => c.CustomerAddr)
- .WithRequired(Ad => Ad.Customer);
- }