admin管理员组

文章数量:1122846

I'm using .NET Core 8 with Entity Framework Core to connect to a PostgreSQL database. I need to create two objects, objectA and objectB, which both reference the same table, but with different filtered data.

The database table structure is: Id, name, category, where the category column can only be 'A' or 'B'.

I want objectA to represent the data from the SQL query: select id, name from teste where categoria = 'A'. Similarly, objectB should represent the data filtered by categoria = 'B'.

I'm getting the following error:

Cannot use table 'teste' for entity type 'objetoA' since it is being used for entity type 'objetoB' and potentially other entity types, but there is no linking relationship. Add a foreign key to 'objetoA' on the primary key properties and pointing to the primary key on another entity type mapped to 'teste'.

I need these models to be separate because I need to instantiate them dynamically at runtime. Does anyone have any ideas on how to resolve this?

I have already tried to create a parent class and inherit the table mapping with both child classes

public class Pai
{
    public string Id { get; set; } = string.Empty;
    public string nome { get; set; } = string.Empty;
    public string categoria { get; set; } = string.Empty;
}

public class objetoA : Pai { }
public class objetoB : Pai { }

na classe AppDbContext.cs

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

    modelBuilder.Entity<Pai>()
        .ToTable("teste")
        .HasKey(p => p.Id);

    modelBuilder.Entity<Pai>()
        .Property(p => p.Id)
        .HasColumnName("Id");

    modelBuilder.Entity<Pai>()
        .Property(p => p.nome)
        .HasColumnName("nome");

    modelBuilder.Entity<Pai>()
        .Property(p => p.categoria)
        .HasColumnName("categoria");

    modelBuilder.Entity<Pai>()
        .HasDiscriminator<string>("categoria")
        .HasValue<ObjetoA>("A")
        .HasValue<ObjetoB>("B")

    modelBuilder.Entity<ObjetoA>()
        .HasBaseType<Pai>();

    modelBuilder.Entity<ObjetoB>()
        .HasBaseType<Pai>();
}

本文标签: