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>();
}
本文标签:
版权声明:本文标题:c# - Entity Framework Core 8 - Mapping Two Entities to the Same Table with Different Filters (PostgreSQL) - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736307246a1933245.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论