Primary key having an identity crisis with Entity Framework

I'm using code first entity framework to create a database. I have two tables, Assignment and AssignmentDetails, both with a primary key called ID. When EF creates the tables, the Assignment ID is made into an identity, but the AssignmentDetails ID is not.

Here are the classes:


public class Assignment
    public int ID { get; set;  }
    public string Line { get; set; }

    public AssignmentDetails Details { get; set; }


public class AssignmentDetails
    public int ID { get; set; }
    public string Details { get; set; }

    public int AssignmentID { get; set; }
    public virtual Assignment Assignment { get; set; }

This is in my OnModelCreatingmethod

    .HasOptional(a => a.Details)
    .WithRequired(d => d.Assignment);

I'm not sure if I set up the 1-to-0..1 relationship up correctly, which could be causing the issue with identities.


Well, in this case, one of the ID is a PK IDENTITY, and the other is a PK/FK (primary key and foreign key at the same time, oh yes).

Where the PK/FK is related to the PK from the other entity (it's at the same time the PK on the entity, and an FK on the other entity's PK, which is IDENTITY).

The purpose of a PK is to be unique, and in this case, it will be unique (as you have a 1-to 0..1 relationship).

And EF, which is lazy, avoids to create a "useless" PK AND a "useless" FK, as the PK is enough for these two roles.

This is a little bit surprising at start (and not always what you would like), but it's coherent.

In practice :

Assignment1 has Id... 1.

AssignmentDetail can have only one Assignment. So you may have a unique autoincremented id as pk for detail + a FK on Assignment, or just use... the Id of Assignment, which is always unique (IDENTITY).

Need Your Help

Parsing HTML with XPath/XMLHttpRequest

javascript xpath xmlhttprequest

I'm trying to download an HTML page, and parse it using XMLHttpRequest(on the most recent Safari browser). Unfortunately, I can't get it to work!