2

Closed

Code First: [InverseProperty] and [ForeignKey] DataAnnotations not working properly.

description

"Repro Steps:
See: http://stackoverflow.com/questions/10020660/why-does-ef-code-first-inverseproperty-attribute-fail-to-work-when-used-with

Actual Results:
Issue 1:EF 4.3.1 - NullReferenceException (EF 4.1 did not have this problem)
Issue 2: An extra Database Column is created for the foreign key that I am already specifying with the DataAnnotation

Expected Results:
Issue 1: No exceptions
Issue 2: A foreign key column should not be auto generated as I am explicitly stating it with a DataAnnotation."

This item was migrated from the DevDiv work item tracking system [ID=397777].

This work item originated from connect.microsoft.com. A member of the EF team at Microsoft should close the related Connect issue when closing this work item.
Closed Sep 23, 2013 at 6:45 PM by RoMiller

comments

BBauer42 wrote Oct 12, 2012 at 12:27 PM

I have the same problem.

RoMiller wrote Jan 25, 2013 at 7:26 PM

EF Team Triage: This may already be fixed in EF6. If not, we should try and fix it.

RoMiller wrote Sep 23, 2013 at 6:41 PM

Confirmed that with EF 4.3.1 the following classes:
public class MyContext : DbContext
{
    public DbSet<Match> Matches { get; set; }
    public DbSet<Player> Players { get; set; }
}

[Table("Matches")]
public class Match
{
    [Key]
    public long Id { get; set; }

    [ForeignKey("Player1Home")]
    public long? HPlayer1Id { get; set; }
    public virtual Player Player1Home { get; set; }
}

[Table("Players")]
public class Player
{
    [Key]
    public long Id { get; set; }

    [InverseProperty("Player1Home")]
    public virtual ICollection<Match> MatchesAsHome1 { get; set; }
}
Incorrectly result in the following database:
CREATE TABLE [Matches] (
    [Id] [bigint] NOT NULL IDENTITY,
    [HPlayer1Id] [bigint],
    [Player1Home_Id] [bigint],
    CONSTRAINT [PK_Matches] PRIMARY KEY ([Id])
)
CREATE INDEX [IX_Player1Home_Id] ON [Matches]([Player1Home_Id])
CREATE TABLE [Players] (
    [Id] [bigint] NOT NULL IDENTITY,
    CONSTRAINT [PK_Players] PRIMARY KEY ([Id])
)
ALTER TABLE [Matches] ADD CONSTRAINT [FK_Matches_Players_Player1Home_Id] FOREIGN KEY ([Player1Home_Id]) REFERENCES [Players] ([Id])

RoMiller wrote Sep 23, 2013 at 6:44 PM

Confirmed that in EF6 (and in EF5) we correctly use the existing FK as configured by the annotations:
CREATE TABLE [dbo].[Matches] (
    [Id] [bigint] NOT NULL IDENTITY,
    [HPlayer1Id] [bigint],
    CONSTRAINT [PK_dbo.Matches] PRIMARY KEY ([Id])
)
CREATE INDEX [IX_HPlayer1Id] ON [dbo].[Matches]([HPlayer1Id])
CREATE TABLE [dbo].[Players] (
    [Id] [bigint] NOT NULL IDENTITY,
    CONSTRAINT [PK_dbo.Players] PRIMARY KEY ([Id])
)
ALTER TABLE [dbo].[Matches] ADD CONSTRAINT [FK_dbo.Matches_dbo.Players_HPlayer1Id] FOREIGN KEY ([HPlayer1Id]) REFERENCES [dbo].[Players] ([Id])