C# 代码优先的一对多或零对多

C# 代码优先的一对多或零对多,c#,entity-framework,ef-code-first,C#,Entity Framework,Ef Code First,这可能很简单,我最终会脸红 class Person { public Guid Id {get;set;} public string Name {get;set;} public Person Manager {get;set;} // The person may or may not have a manager. public Guid? ManagerId {get;set;} // I need the Guid if the Person has a manage

这可能很简单,我最终会脸红

class Person {
  public Guid Id {get;set;}
  public string Name {get;set;}
  public Person Manager {get;set;} // The person may or may not have a manager.
  public Guid? ManagerId {get;set;} // I need the Guid if the Person has a manager
}
我试过了
modelBuilder.Entity().has可选(e=>e.Manager)。WithMany().HasForeignKey(e=>ManagerId)

但是这没有任何好处。

您是否尝试过不使用任何自定义关系映射?我原以为ef会自动为你创造奇迹

如果不更改类,则不需要配置任何关系。可能是ef代码首先不喜欢GUID

class Person {
  public int Id {get;set;}
  public string Name {get;set;}
  public Person Manager {get;set;}
  public int? ManagerId {get;set;}
}

使用guid而不是int是否有特定的原因?

是否尝试过不使用任何自定义关系映射?我原以为ef会自动为你创造奇迹

如果不更改类,则不需要配置任何关系。可能是ef代码首先不喜欢GUID

class Person {
  public int Id {get;set;}
  public string Name {get;set;}
  public Person Manager {get;set;}
  public int? ManagerId {get;set;}
}

使用guid而不是int是否有特定的原因?

您可以尝试使用数据注释来帮助EF推断关系。现在无法测试此功能,因此它可能无法工作,但类似于:

class Person {
  public Guid Id {get;set;}
  public string Name {get;set;}

  [ForeignKey("Id")]
  public virtual Person Manager {get;set;} 
  public Guid? ManagerId {get;set;}
}

您可以尝试使用数据注释来帮助EF推断关系。现在无法测试此功能,因此它可能无法工作,但类似于:

class Person {
  public Guid Id {get;set;}
  public string Name {get;set;}

  [ForeignKey("Id")]
  public virtual Person Manager {get;set;} 
  public Guid? ManagerId {get;set;}
}

您不能从Person.Manager.ID获取经理ID,而不是使用Person.ManagerId吗?除非GUID在这两种情况下有所不同,否则我不明白为什么要将其存储两次。您不能从Person.Manager.ID获取经理ID而不是使用Person.ManagerId吗?除非GUID在这两种情况下有所不同,否则我不明白为什么要将其存储两次。我需要对断开连接的数据进行操作,GUID似乎是最佳选项。我需要对断开连接的数据进行操作,GUID似乎是最佳选项。