views:

82

answers:

1

Hi all,

I have run into a scenario where Entity Framework 4.0 does not generate an association to an entity backed by a table having a unique index, and I am wondering why.

The basic setup is this: Let's say I have two tables in SQL Server 2008 R2 and a foreign key relation:

CREATE TABLE [dbo].[User](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [GroupId] [int] NULL,
 CONSTRAINT [PK_User] 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]

CREATE TABLE [dbo].[Group](
[Id] [int] IDENTITY(1,1) NOT NULL,
 CONSTRAINT [PK_Group] 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]

ALTER TABLE [dbo].[User]  WITH CHECK ADD  CONSTRAINT [FK_User_Group] 
    FOREIGN KEY([GroupId])
REFERENCES [dbo].[Group] ([Id])

Moreover, assume the following index is present:

CREATE NONCLUSTERED INDEX [IX_Group] ON [dbo].[Group] 
(
[Id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]

If I tell the designer in Visual Studio 2010 to generate an ADO.NET Entity Data Model I get a model with two classes, User and Group, User having a Navigation Property called Group. That is all fine and well.

Now, let's say instead that the index looked like this:

CREATE UNIQUE NONCLUSTERED INDEX [IX_Group] ON [dbo].[Group] 
(
    [Id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]

That is, the only thing I have done is make the index a unique index. Having done this, when I tell Visual Studio's designer to generate an Entity Model, the association between users and groups doesn't show up and the User has no navigation properties. Inspecting the generated EDMX file reveals that the storage model has no AssociationSet at all.

Can anyone explain why this is? Why does the unique index prevent EF from modeling the relationship?

Thank you.

+2  A: 

A unique index allows for 1 NULL value, a primary key doesn't allow NULLS. How will you match the NULL when nothing is equal to NULL not even another NULL

SQLMenace
Hmm, maybe you are right, but Linq2SQL can handle this scenario. Also, I can add appropriate AssociationSets etc. in the EDMX by hand and it will work fine, so I still don't understand why EF gives up.
Rune