【问题标题】:The property 'Entity1.Entity2' is of type 'Entity2' which is not supported by current database provider属性“Entity1.Entity2”的类型为“Entity2”,当前数据库提供程序不支持
【发布时间】: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 时,我得到了不同之处

标签: entity-framework-core


【解决方案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 });
}

【讨论】:

    猜你喜欢
    • 2017-04-22
    • 2010-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-15
    • 2020-06-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多