Entity framework 如何不在EF中映射外键id(代码优先)?
好的,让我先解释一下这不是我的代码。我要从另一个员工那里接管一个项目。无论如何,这个项目首先使用的是代码。我正在修复一个性能问题,但我遇到了一个奇怪的错误 我基本上有两个映射类要处理。为了简洁起见,我会编一些简短的版本Entity framework 如何不在EF中映射外键id(代码优先)?,entity-framework,ef-code-first,Entity Framework,Ef Code First,好的,让我先解释一下这不是我的代码。我要从另一个员工那里接管一个项目。无论如何,这个项目首先使用的是代码。我正在修复一个性能问题,但我遇到了一个奇怪的错误 我基本上有两个映射类要处理。为了简洁起见,我会编一些简短的版本 public class User { public int UserId { get; set; } //primary key //attributes here, not important public int UserProfileId { g
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
modelBuilder.Entity().ToTable(“应用程序用户”);
然后,使用名称将每个列映射到拉入表的一列。
但是,我试图将这两个表合并成一对一的关系,如下所示:
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
modelBuilder.Entity().HasRequired(x=>x.UserProfile)
.有很多
.HasForeignKey(u=>u.UserProfileId)//此处出错-原始表中不存在此列
现在,据我所知,错误是在上一个表中,没有(UserProfileId)的外键列,因此我得到了一个无效的列名错误
有没有办法不映射外键id列而仍然保持一对一的关系?既然你说用户表上没有UserProfileId,你就定义了一个1:1的关系,其中用户和UserProfile表共享一个主键 如果是这样,您可以这样映射它:
modelBuilder.Entity<User>()
.HasRequired(u => u.UserProfile)
.WithRequiredPrincipal();
modelBuilder.Entity()
.HasRequired(u=>u.UserProfile)
.WithRequiredPrincipal();
这将生成一个如下所示的数据库:
modelBuilder.Entity<User>()
.HasRequired(u => u.UserProfile)
.WithRequiredPrincipal();
既然您说用户表上没有UserProfileId,那么您定义的是1:1关系,其中用户和UserProfile表共享一个主键,对吗 如果是这样,您可以这样映射它:
modelBuilder.Entity<User>()
.HasRequired(u => u.UserProfile)
.WithRequiredPrincipal();
modelBuilder.Entity()
.HasRequired(u=>u.UserProfile)
.WithRequiredPrincipal();
这将生成一个如下所示的数据库:
modelBuilder.Entity<User>()
.HasRequired(u => u.UserProfile)
.WithRequiredPrincipal();
您的
应用程序是否为用户
FK添加到UserProfile
表?或者UserProfile
的主键也是FK toapplication\u user
?您的application\u user
是否是FK toUserProfile
表?或者UserProfile
的主键也是对application\u user
的FK?