Wednesday, November 8, 2017

bridge tables in Entity Framework's .edmx paradigm and how they behave in code

You could have a many-to-may relationship between clowns and Car with a bridge table made like so. Note that the primary key is a combination of the two primary keys from the Clown table and the Car table and that there is not otherwise a primary key named for the bridge table itself nor any other columns beyond the two that loop in Car and clowns.

CREATE TABLE [dbo].[ClownToCarBridge](
   [ClownID] [uniqueidentifier] NOT NULL,
   [CarID] [uniqueidentifier] NOT NULL,
   CONSTRAINT [PK_ClownToCarBridge] PRIMARY KEY CLUSTERED
   (
      [ClownID] ASC,
      [CarID] ASC
   )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF,
   IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON,
   ALLOW_PAGE_LOCKS = ON)
)
GO
ALTER TABLE [dbo].[ClownToCarBridge] WITH CHECK
ADD CONSTRAINT [FK_ClownToCarBridge_ClownID] FOREIGN KEY([ClownID])
REFERENCES [dbo].[Clown] ([ClownID])
GO
ALTER TABLE [dbo].[ClownToCarBridge]
CHECK CONSTRAINT [FK_ClownToCarBridge_ClownID]
GO
ALTER TABLE [dbo].[ClownToCarBridge] WITH CHECK
ADD CONSTRAINT [FK_ClownToCarBridge_CarID] FOREIGN KEY([CarID])
REFERENCES [dbo].[Car] ([CarID])
GO
ALTER TABLE [dbo].[ClownToCarBridge]
CHECK CONSTRAINT [FK_ClownToCarBridge_CarID]
GO

 
 

The way this materializes in code is interesting. There is no ClownToCarBridge C# class. Instead, the Car object will have as a new getsetter an ICollection of Clown objects called "Clowns" and the Clown object will have as a new getsetter, you guessed it, an ICollection of Car objects dubbed: "Cars"

No comments:

Post a Comment