gpt4 book ai didi

ef-code-first - EF Code First - Fluent API(WithRequiredDependent 和 WithRequiredPrincipal)

转载 作者:行者123 更新时间:2023-12-04 05:59:22 27 4
gpt4 key购买 nike

我有以下类(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; }
}

要点:
  • BrideGroom需要属性
  • 一对一的关系
  • User类,是Couple需要

  • OnModelCreating 中的 DbContext
    modelBuilder.Entity<User>().HasRequired(u => u.Couple).WithRequiredPrincipal();
    modelBuilder.Entity<Couple>().HasRequired(u => u.Bride).WithRequiredDependent();
    modelBuilder.Entity<Couple>().HasRequired(u => u.Groom).WithRequiredDependent();

    但我不能被要求!

    数据库中的所有文件都为空!。

    如何将数据库中的字段设为非空?
    如果可能,请使用 API Flient .

    最佳答案

    应该是这样的:

    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



    重要提示:你不认为你想要的配置会产生死锁吗?我没有测试过上面的代码,但这个配置对我来说似乎是一个死锁,所以我不确定 EF 是否允许你创建它。用户必须需要一对夫妇,我猜夫妇必须需要同一个用户。

    关于ef-code-first - EF Code First - Fluent API(WithRequiredDependent 和 WithRequiredPrincipal),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7742131/

    27 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com