1
好的,让我先解释一下,这不是我的代码。我正在接管另一名员工的项目。无论如何,这个项目正在使用Code First。我正在解决性能问题,但我得到一个奇怪的错误。如何不在EF中映射外键id(代码优先)?
我基本上有两个映射类来处理。我会编写简短的版本来简洁。
public class User
{
public int UserId { get; set; } //primary key
//attributes here, not important
public int UserProfileId { get; set; } //foreign key id *i added this*
public UserProfile UserProfile { get; set; } //foreign key *i added this*
}
public class UserProfile
{
public int Id { get; set; } //primary key
//attributes here, not important
}
现在,这是一个非常标准的外键关系。但是,有一个警告。这些表正在从旧表中删除,如下所示:
modelBuilder.Entity<User>().ToTable("application_user");
然后,使用名称将每个列映射到拉动的表的列。 不过,我想这两个表合并成一比一的关系,像这样:
modelBuilder.Entity<User>().HasRequired(x => x.UserProfile)
.WithMany()
.HasForeignKey(u => u.UserProfileId); //ERROR HERE - THIS COLUMN DOES NOT EXIST IN THE ORIGINAL TABLE
现在,错误,据我所知道的是,在上表中, (UserProfileId)没有外键列,所以我得到一个无效的列名错误。
有没有一种方法,我可以不映射外键id列,仍然保持一对一的关系?
贵'application_user'一个FK为'UserProfile'表?或者'UserProfile'的PK也是'application_user'的FK? – Eranga