开发者

One or zero to many with code first

This is probably very simple and I'll end up with a red face...

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
}

I trie开发者_StackOverflowd modelBuilder.Entity<Person>().HasOptional(e=>e.Manager).WithMany().HasForeignKey(e=>ManagerId) but that didn't do any good.


Have you tried without any custom relationship mapping? I would have thought the ef would automatically do it's magic for you.

If not change you class as folows and you won't need to configure any of the relationships. It might be ef code first does not like guids

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

Do you have a specific reason for using a guid and not int?


You could try using data annotations to help EF infer the relationship. Can't test this now so it probably wont work, but something like:

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;}
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜