Search code examples
sqlentity-frameworklinq-to-entitiesedmxef-database-first

How can a 1 to 1 / 1 to 0..1 relationship in Entity Framework 6.1 be created from Database First?


I have a Database First generated edmx project.

How could I add add a 1:1 or 1:0..1 relationship to either the edmx, or the database (and therefore the edmx)?

N.B.
I have rooted through the search engines looking for how to create 1:1 or 1:0..1 associations in Entity Framework 6.1; Most mention Code First, some mention a Model first approach and almost all of them mention a fluent API.

I've looked through various similar Stack Overflow questions and they also mention code first; code first is not an option in my case.

I've not found a single article mentioning if this is doable in Database First.

Thanks :)


Solution

  • I've resolved how to create a 1:0..1 relationship in Database First.

    For the two tables (in this example, Tbl_A and Tbl_A_Proxy), It requires that one table's primary key is not IDENTITY(1,1), and that its primary key is foreign key'd to the primary key of the other table.

    There are probably other ways but this is how I resolved it.

    USE [Database]
    GO
    
    SET ANSI_NULLS ON
    GO
    
    SET QUOTED_IDENTIFIER ON
    GO
    
    SET ANSI_PADDING ON
    GO
    
    CREATE TABLE [dbo].[Tbl_A]
    (
        [id] [int] IDENTITY(1,1) NOT NULL,
        [Name] [varchar](255) NOT NULL,
     CONSTRAINT [PK_Tbl_A] PRIMARY KEY CLUSTERED 
    (
        [id] ASC
    )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
    ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
    
    GO
    
    CREATE TABLE [dbo].[Tbl_A_Proxy]
    (
        [id] [int] NOT NULL,
     CONSTRAINT [PK_Tbl_A_Proxy] PRIMARY KEY CLUSTERED 
    (
        [id] ASC
    )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
    ) ON [PRIMARY]
    
    GO
    
    ALTER TABLE [Database].[dbo].[Tbl_A_Proxy]
    ADD CONSTRAINT [FK_Tbl_AProxy]
    FOREIGN KEY ([id])
    REFERENCES [Database].[dbo].[Tbl_A]([id])