EF Code First - Fluent API (WithRequiredDependent

2019-04-23 13:14发布

问题:

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:

  1. Bride and Groom properties are required
  2. One-to-one relationship
  3. In the User class, it is Couple required

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 not be required!

All fileds are with null in the database!.

How do I get the fields in the database as not null? If possible using the API Flient.

回答1:

It should be 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 relationship to be required:required without a navigation property on the other side of the relationship. The entity type being configured will be the dependent and contain a foreign key to the principal. The entity type that the relationship targets will be the principal in the relationship.


Meaning : Let's consider your first line of code here. It creates a foreign key in the entity being configured (User) making it Dependant and making the other side of the relationship (Couple) Principal


Important : Don't you think the configuration you desire will generate a deadlock? I've not tested the code above, but this configuration seems to be a deadlock to me so i'm not sure if EF would allow you to create it. User must need a Couple, and Couple must need that same user i guess.