【发布时间】:2019-12-02 08:33:37
【问题描述】:
我正在尝试使用代码优先创建初始迁移。我有 2 个实体类如下:
public class Entity1
{
public string Id { get; set; }
}
public class Entity2
{
public Entity1 Entity1 { get; set; }
public int Order { get; set; }
}
和我的DbContext如下;
public class AppDbContext : DbContext
{
public DbSet<Entity1> Entity1List { get; set; }
public DbSet<Entity2> Entity2List { get; set; }
public AppDbContext(DbContextOptions options) : base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder
.Entity<Entity2>()
.HasKey(c => new { c.Entity1, c.Order });
}
}
当我尝试使用
创建迁移时add-migration InitialMigration
我得到了错误;
The property 'Entity2.Entity1' is of type 'Entity1' which is not supported by current database provider. Either change the property CLR type or ignore the property using the '[NotMapped]' attribute or by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating'.
【问题讨论】:
-
Entity1不能成为密钥的一部分。 -
我很确定可以将外键变成主键或复合键的一部分。我只是不知道如何指定它。
-
Entity1不是外键。这是一个参考。您需要将Entity1Id添加到班级。 -
@GertArnold 谢谢。我认为 EF 将其视为外键。当我在这里阅读 docs.microsoft.com/en-us/ef/core/modeling/relationships 时,我得到了不同之处