本文介绍了EF代码优先 - 流畅的API(WithRequiredDependent and WithRequiredPrincipal)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下类:

  public class User 
{
public Guid Id {get;组; }
public string Name {get;组; }
public夫妇{get;组;
}

public class Couple
{
public Guid Id {get;组; }
public User Groom {get;组; }
public User Bride {get;组;
}

重点:


  1. 新娘 Groom 属性是必需的

  2. 一对一的关系

  3. 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

解决方案

应该是这样的: p>

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








重要提示:你认为你想要的配置会产生一个僵局吗?我没有测试上面的代码,但这个配置似乎是一个死锁给我,所以我不知道如果EF允许你创建它。用户必须需要一对夫妇,而夫妇必须需要同样的用户。


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.

解决方案

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();



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.

这篇关于EF代码优先 - 流畅的API(WithRequiredDependent and WithRequiredPrincipal)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 23:44