user1933072
user1933072

Reputation: 101

Creating composite primary key using entity framework 4.1

I have two tables Projects and Task. Task is a weak entity of a project, so the composite primary key of task is (ProjectId & TaskID). I tried doing so with the following code, but it gives an error

Cannot define PRIMARY KEY constraint on nullable column in table 'Tasks'.

I'm using code-first approach to create the tables and I've ensured that the column is not null, but it's still not working. Please help!

public class Task
{
    [ForeignKey("ProjectId")]
    public Project Project { get; set; }
    [Required]
    public int ProjectId { get; set; }

    //[Key, Column(Order = 1)]
    [Required]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public virtual int TaskID { get; set; }
    ...
}

//using FluentAPI
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);

    modelBuilder.Entity<Task>().HasRequired(p => p.Project);
    modelBuilder.Entity<Task>().HasKey(p => new { p.ProjectId, p.TaskID });

    modelBuilder.Entity<Project>()
           .HasRequired(e=> e.Employee)
           .WithMany()
            .WillCascadeOnDelete(false);
}

Upvotes: 10

Views: 19298

Answers (1)

Dan
Dan

Reputation: 1480

Came across this looking for something else, bit late, but this maps fine to a composite key for me

    [Key, Column(Order=1) ]
    public int KeyId { get; set; }
    [Key, Column(Order = 2)]
    public int Key1Id { get; set; }
    [Key, Column(Order = 3)]
    public int Key2Id  { get; set; }
    [Key, Column(Order = 4)]
    public int Key3Id  { get; set; }

Hope this helps someone.

Upvotes: 34

Related Questions