There are, say, an Attachments table with columns: id | ownerId | ownerType id | ownerId | ownerType id | ownerId | ownerType , which, respectively: primary key, foreign key and the table to which the foreign key belongs.

For example:

  id | ownerId | ownerType --------------------------------- 1 1 Post 2 1 Comment 

Can EntityFramework be able to organize a link so that the output in the essence of the post and comment is a collection with their attachments? Sort of:

 builder.Entity<Post>(). .HasMany(p => p.Attachments) .WithOne() .HasForeignKey(a => a.OwnerId); // and a.OwnerType = "Post" 

UPD: In the comments they advised to simply add the property of the collection of attachments to the necessary entities and entrust the rest to the EF itself. That's exactly what I did.

And then I wanted to add a third entity with attachments.

enter image description here

Does this solution look a bit strange? Already 3 foreign keys.

  • EntityFramework does not support this feature, if only because c # is a strongly typed language. What type would you expect the associated object to have in this case? - user218976
  • @Anamnian, because here, in addition to the condition of coincidence of the foreign key, the filter condition on the table is added. And then the problem of typing? One could create two absolutely identical attachment tables (one for posts, another for comments) and leave only OwnerId , just not sure that producing two identical tables is the right way out = / - MrModest
  • Post and Comment have a common ancestor? - Andrew NOP
  • one
    Why not just make a collection with an Attachment in the Post and Comment , and entrust the implementation of this to EF? Trying to save on matches? - Andrew NOP
  • one
    Of course. As correctly noted above, you do not need to think about implementation in the database with Code First (until you clearly encounter performance problems) - Andrey NOP

0