属性“ Entity1.Entity2”的类型为“ Entity2”,当前数据库提供程序不支持

时间:2019-12-01 15:23:05

标签: entity-framework-core

我正在尝试使用代码优先创建初始迁移。我有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'.

1 个答案:

答案 0 :(得分:1)

也许您正在尝试使Entity1的主键成为Entity2的复合主键的一部分。因此,您的Entity2应该如下:

public class Entity2
{
    public string Entity1Id { get; set; }
    public int Order { get; set; }

    public Entity1 Entity1 { get; set; }
}

然后在OnModelCreating中进行如下操作:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);

    modelBuilder
        .Entity<Entity2>()
        .HasKey(c => new { c.Entity1Id, c.Order });
}