我已将IdentityUser.Id
属性的类型从string
更改为Guid
,并添加了与基类LogEntry
的关系,该基类具有派生类{{1} }和JournalEntry
。
当我尝试Weight Entry
时,我收到以下错误:
System.Data.SqlClient.SqlException:Column' AspNetUsers.Id'与引用列' LogEntries.ApplicationUserId'不同的数据类型在外键' FK_LogEntries_AspNetUsers_ApplicationUserId'。无法创建约束或索引。查看以前的错误。
实体框架应该创建Update-Database
表,其中AspNetUsers
字段的类型为Id
,但事实并非如此。它是使用uniqueidentifier
创建的。
我在下面列出了相关的源代码:
ApplicationUser.cs
nvarchar(450)
LogEntry.cs
public class ApplicationUser : IdentityUser<Guid>
{
public ApplicationUser()
: base()
{
Id = Guid.NewGuid();
}
public virtual ICollection<LogEntry> LogEntries { get; set; }
}
JournalEntry.cs
public abstract class LogEntry
{
public virtual Guid Id { get; set; }
public virtual DateTime CreatedDt { get; set; }
public virtual Guid ApplicationUserId { get; set; }
public virtual ApplicationUser ApplicationUser { get; set; }
}
JournalEntry.cs
public class JournalEntry : LogEntry
{
public string Text { get; set; }
}
ApplicationDbContext.cs
public class WeightEntry : LogEntry
{
public short Kilograms { get; set; }
}
Startup.cs ConfigureServices
public class ApplicationDbContext : IdentityDbContext<ApplicationUser, IdentityRole<Guid>, Guid>
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
DbSet<JournalEntry> JournalEntries { get; set; }
DbSet<WeightEntry> WeightEntries { get; set; }
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.Entity<ApplicationUser>(x =>
{
x.HasMany(y => y.LogEntries)
.WithOne(y => y.ApplicationUser)
.HasForeignKey(y => y.ApplicationUserId)
.HasPrincipalKey(y => y.Id)
.IsRequired();
});
builder.Entity<LogEntry>(x =>
{
x.ToTable("LogEntries");
x.HasOne(y => y.ApplicationUser)
.WithMany(y => y.LogEntries)
.HasForeignKey(y => y.ApplicationUserId)
.HasPrincipalKey(y => y.Id)
.IsRequired();
});
builder.Entity<JournalEntry>(x =>
{
x.ToTable("JournalEntries");
});
builder.Entity<WeightEntry>(x =>
{
x.ToTable("WeightEntries");
});
}
}