Entity Framework Core: One-Way Navigation Property without a Foreign Key

675 Views Asked by At

My class configuration looks like this:

class Item {
  Guid ParentId { get; set; }
  // ... 
}

class ClassWithItemCollectionA {
  Guid Id { get; set; }
  ICollection<Item> Items { get; set; }
  // ...
}

class ClassWithItemCollectionB {
  Guid Id { get; set; }
  ICollection<Item> Items { get; set; }
  // ...
}

I would like to populate ClassWithItemCollectionA.Items and ClassWithItemCollectionB.Items navigation properties joining the entities with Item.ParentId -> ClassWithItemCollectionA.Id and Item.ParentId -> ClassWithItemCollectionB.Id.

I have tried with different approaches, but I've ended up getting undesirable results.

  • If I let EF Core create the navigation properties it creates an extra column for every entity type I add an Item collection to.
  • If I force EF Core to use ParentId as foreign key it creates the database schema without extra columns, but creates extra constraints that prevent me from inserting anything in the Item table.
  • I could make Items collection unmapped and do an extra query to populate it for every ClassWithItemCollectionX, incurring into the N+1 problem.

Is there any way to define a base class like this:

class BaseClassWithItemCollection {
  Guid Id { get; set; }
  ICollection<Item> Items { get; set; }
}

and then specify how to retrieve the Items collection, or any other way to achive what I'm looking for?

0

There are 0 best solutions below