Q:

Cannot insert duplicate key. Composite Primary key. ASP.NET Entity Framework

I'm trying to create application using Entity Framework.
There's what I want to do (every entity has Id as well): 

I want to use composite primary key in this case (PatientId + DiagnosisId).
There's a collection of Diagnoses in Patient model class: 
public ICollection<Diagnosis> Diagnoses { get; set; }

public class Diagnosis
{
    [Required]
    [MaxLength(200)]
    public String Type { get; set; }
    public String Complications { get; set; }
    public String Details { get; set; }

    public Int32 DiagnosisId { get; set; }

    public Patient Patient { get; set; }
    public Int32 PatientId { get; set; }
}

Also in the database context I defined 
public DbSet<Diagnosis> Diagnoses { get; set; }

and 
modelBuilder.Entity<Diagnosis>().HasKey(x => new { x.DiagnosisId, x.PatientId });

in OnModelCreating method to create the composite primary key.
In an ASP.NET MVC CRUD controller I create Diagnosis and every time DiagnosisId is the same = 0. And I can't paste new data to database because it's like duplicate. That's my create post method on Pastebin if it could help

A:

The parent key goes first:
modelBuilder.Entity<Diagnosis>().HasKey(x => new { x.PatientId, x.DiagnosisId });

Because you want all the Diagnoses for a particular Patent to be stored together.
And you need to request that the key is generated by the database.  For EF Core its:
modelBuilder.Entity<Diagnosis>().Property(r => r.DiagnosisId).ValueGeneratedOnAdd();

for EF6 it's:
modelBuilder.Entity<Diagnosis>().Property(r => r.DiagnosisId).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);

