Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
255 views
in Technique[技术] by (71.8m points)

Entity Framework One Way Relationship .Net Core 3.1

I have the following tables in PostgreSQL:

entity_a:
  identifier integer, --PK
  name varchar(256),
  entity_b integer --FK

entity_b:
  identifier integer, --PK
  name varchar(256)

My models look like:

[Table("entity_a")]
public class EntityA
{
  [Column("identifier")]
  [Key]
  [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
  public int Identifier { get; set; }

  [Column("name")]
  public string Name { get; set; }

  [Column("entity_b")]
  [ForeignKey("EntityB")]
  public EntityB EntityB { get; set; }
}

[Table("entity_b")]
public class EntityB
{
  [Column("identifier")]
  [Key]
  [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
  public int Identifier { get; set; }

  [Column("name")]
  public string Name { get; set; }
}

When I select data from the database, the EntityB value inside EntityA is always null. I only want one way relationship, where EntityA knows about EntityB. What am I doing wrong?

There is a foreign key constraint set in the database as well to model the relationship.

I have tried creating a Entity_B_Id property inside EntityA as well, but this only set the id of Entity_B_Id but not the actual object (i.e. EntityB was null):

[Table("entity_a")]
public class EntityA
{
  ...
  [Column("entity_b")]
  [ForeignKey("EntityB")]
  public int Entity_B_Id { get; set; }
  public EntityB EntityB { get; set; }
}
question from:https://stackoverflow.com/questions/65879562/entity-framework-one-way-relationship-net-core-3-1

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

EF Core won't automatically include related entities. All related entities must either be eagerly loaded (via Include) or explicitly loaded (Load).

Documents for reference:

https://docs.microsoft.com/en-us/ef/core/querying/related-data/eager#eager-loading

https://docs.microsoft.com/en-us/ef/core/querying/related-data/explicit#explicit-loading


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...