EF Code First - Fluent API (WithRequiredDependent and WithRequiredPrincipal)

巧了我就是萌 提交于 2019-12-22 04:33:21

问题


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.



来源:https://stackoverflow.com/questions/7742131/ef-code-first-fluent-api-withrequireddependent-and-withrequiredprincipal

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!