为什么 Code First 实体框架生成外键?
所以我有......
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是一对一的关系。仅当外键构建在主键之上时它才有效。你需要这样的东西:
如果经理有一个用户,用户必须具有与经理相同的PK值。您将无法在双方都定义此类关系可选,因为这会违反 FK。在流畅的映射中,您应该执行以下操作:
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:
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: