Question

Imagine that I have three entities (EntityA, EntityB, EntityC) that can have some images. So there are two ways:

  1. Make an image table for each entity. It means that EntityA has a image table named AImages and similarly for EntityB and EntityC. This method is more intelligent but has more tables.

  2. Have an image table and another table name EntityType that goes between.

EntityType table has an EntityTypeId column and a name and has three records: 1,EntityA, 2,EntityB, 3,EntityC.

Then in image table:

If I save a record for EntityA the record in image table would be this: 1,1,name

First column is ImageId, second one is EntityTypeId and the third one is image's filename.

If I save a record for EntityB the record in image table would be this: 2,2,name

And if I save a record for EntityA the record in image table would be this: 3,3,name

In this method the number of tables would decrease but the queries would be longer.

Which one is optimised or any other way...

Was it helpful?

Solution

Have an image table and another table name EntityType that goes between.

This will require you to enforce the referential integrity manually, which is trickier than it looks.

So either:

  • for each 1:N relationship, have a separate "N" table for each "1" table (as you proposed),
  • or employ something like exclusive FK or inheritance if you want to avoid too much structural duplication.

OTHER TIPS

The raght way is to store images in varbinary(max) columns in their respective tables, and not to separate them. SQL Server will take care of phisically storing them in an efficient, off-row, manner.

Depending on which version of SQL Server is used and the size of the LOBs, you might consider FILESTREAM or FILETABLE feature.

It seems having an BaseEntity table, that contains shared properties of other entities, will help you.
EntityA & EntityB & EntityC will be childes of the BaseEntity, their primary key will be the primary key of EntityBase table.
A zero-or-one relation between them will do.
Having a discriminator column called entyty_type in BaseEntity will be recommanded.

Other collections like Images and adresses and else will be connected to this EntityBase table.
enter image description here

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top