在我的PersonModel中,我删除了一个我不再使用的属性。我还确保从代码中删除关系。但是,当我再次运行应用程序时,应用程序失败,因为DbSet仍然引用旧列。正在生成的查询如下:
{SELECT
[Extent1].[StatusId] AS [StatusId],
[Extent1].[Id] AS [Id],
// some data
[Extent1].[UserInformation_Id] AS [UserInformation_Id] // this is no longer in the model
FROM [dbo].[User] AS [Extent1]}
为了进一步调查,我创建了一个迁移脚本,我注意到它生成了一个重命名列行:
RenameColumn(table: "dbo.User", name: "UserInformationId", newName: "UserInformation_Id");
我的假设如下:
问题与此类似:
EF Code First adds extra column to query that doesn't exist in model anymore
有关此问题可能发生错误的任何帮助吗?
更新
这是我的代码:
用户类
public partial class User
{
public long Id { get; set; }
public Guid UserKey { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public virtual ICollection<UserInformation> UserInformations { get; set; }
}
用户映射
public class UserMap : EntityTypeConfiguration<User>
{
public UserMap()
{
// Primary Key
this.HasKey(t => t.Id);
// Properties
this.Property(t => t.Username)
.IsRequired()
.HasMaxLength(255);
this.Property(t => t.Password)
.IsRequired();
// Table & Column Mappings
this.ToTable("User");
this.Property(t => t.Id).HasColumnName("Id");
this.Property(t => t.UserKey).HasColumnName("UserKey");
this.Property(t => t.Username).HasColumnName("Username");
this.Property(t => t.Password).HasColumnName("Password");
}
}
UserInformation Class
public partial class UserInformation
{
public long Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
// This is the column that hold relationship to the User table.
public long UserId { get; set; }
public virtual User User { get; set; }
}
UserInformation Mapping
public class UserInformationMap : EntityTypeConfiguration<UserInformation>
{
public UserInformationMap()
{
// Primary Key
this.HasKey(t => t.Id);
// Properties
this.Property(t => t.FirstName)
.HasMaxLength(100);
this.Property(t => t.LastName)
.HasMaxLength(50);
// Table & Column Mappings
this.ToTable("UserInformation");
this.Property(t => t.Id).HasColumnName("Id");
this.Property(t => t.FirstName).HasColumnName("FirstName");
this.Property(t => t.LastName).HasColumnName("LastName");
this.Property(t => t.UserId).HasColumnName("UserId");
// Relationships
this.HasRequired(t => t.User)
.WithMany(t => t.UserInformations)
.HasForeignKey(d => d.UserId);
}
}
答案 0 :(得分:0)
首先,你的第一个假设是错误的。迁移生成器实际上会查看数据库中的表,主要是因为它无法对您在代码中所做的更改产生差异。因此,它将在内存中生成新模型,并与数据库中的任何内容进行比较。
关于您看到的迁移,我怀疑还有一些推动EF生成外键(即使您无法在代码中访问它)。也许像UserInformation => User
这样的导航属性? (只是一个猜测,向我们展示一些数据模型的代码以获得更好的答案)