EF Code First - Fluent API (WithRequiredDependent and WithRequiredPrincipal)

I have the following class:

public class User { public Guid Id { get; set; } public string Name { get; set; } public Couple Couple { get; set; } } public class Couple { public Guid Id { get; set; } public User Groom { get; set; } public User Bride { get; set; } } 

Important points:

  • Bride and Groom properties required
  • One-to-one relationships
  • User class requires Couple

DbContext in OnModelCreating

 modelBuilder.Entity<User>().HasRequired(u => u.Couple).WithRequiredPrincipal(); modelBuilder.Entity<Couple>().HasRequired(u => u.Bride).WithRequiredDependent(); modelBuilder.Entity<Couple>().HasRequired(u => u.Groom).WithRequiredDependent(); 

But I can’t be obligatory!

All records with zero value in the database!

How to get fields in a database as non-empty? If possible using the Flient API .

+8
entity-relationship ef-code-first fluent-interface
source share
1 answer

It should be like this:

 modelBuilder.Entity<User>().HasRequired(u => u.Couple).WithRequiredDependent(); modelBuilder.Entity<Couple>().HasRequired(u => u.Bride).WithRequiredDependent(); modelBuilder.Entity<Couple>().HasRequired(u => u.Groom).WithRequiredDependent(); 

How WithRequiredDependent Works . Configures the required relationship: required without the navigation property on the other side of the relationship. The type of custom object will be dependent and contain the foreign key for the principal. Person enter that the goal of the relationship will be primary in the relationship.


Meaning : consider your first line of code here. It creates a foreign key in a custom object ( User ), making it dependent and creating the other side of the relationship ( Pair )


Important: Don't you think the configuration you want will create a dead end? I have not tested the code above, but this configuration seems to be a dead end for me, so I'm not sure if EF will let you create one. The user must need a pair, and the pair needs the same user that I assume.

+5
source share

All Articles