为什么 Code First 实体框架生成外键?

发布于 2024-11-07 02:40:04 字数 433 浏览 1 评论 0原文

所以我有......

public class User
{
   public int ManagerId { get; set; }
   public Manager Manager { get; set; }
}

public class Manager
{
   public User User { get; set; }
}

modelBuilder.Entity<User>()
.HasOptional(x => x.Manager)
.WithOptionalDependent(x => x.User);

因此,用户有一个可选的经理,而经理可能有也可能没有用户。这是有效的,因为管理器没有用户的外键,但用户有管理器的可为空的外键。但它生成外键并将 ManagerId 视为常规属性。我该如何解决这个问题?

干杯,伊恩。

So I've got...

public class User
{
   public int ManagerId { get; set; }
   public Manager Manager { get; set; }
}

public class Manager
{
   public User User { get; set; }
}

modelBuilder.Entity<User>()
.HasOptional(x => x.Manager)
.WithOptionalDependent(x => x.User);

Thus a user has an optional Manager and a Manager may or may not have a User. This works in that Manager doesn't have a foreign key to a User but a User has a nullable foreign key to a Manager. But its generating the foreign key and treating ManagerId as a regular property. How do I fix this?

Cheers, Ian.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

为人所爱 2024-11-14 02:40:04

这是一对一的关系。仅当外键构建在主键之上时它才有效。你需要这样的东西:

public class User
{
   [Key, ForeingKey("Manager")]
   public int Id { get; set; }
   public Manager Manager { get; set; }
}

public class Manager
{
   public int Id { get; set; }
   public User User { get; set; }
}

如果经理有一个用户,用户必须具有与经理相同的PK值。您将无法在双方都定义此类关系可选,因为这会违反 FK。在流畅的映射中,您应该执行以下操作:

modelBuilder.Entity<Manager>()
            .HasOptional(m => m.User)
            .WithRequired(u => u.Manager);

It is one-to-one relation. It works only if the foreign key is built on top of primary key. You need something like this:

public class User
{
   [Key, ForeingKey("Manager")]
   public int Id { get; set; }
   public Manager Manager { get; set; }
}

public class Manager
{
   public int Id { get; set; }
   public User User { get; set; }
}

If manager has a user, user must have the same PK value as manager. You will not be able to define such relation optional on both sides because it would violate FK. In fluent mapping you should do something like:

modelBuilder.Entity<Manager>()
            .HasOptional(m => m.User)
            .WithRequired(u => u.Manager);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文