Creating a composite primary key using entity structure 4.1

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

Unable to determine PRIMARY KEY constraint for a column with a null value in the Tasks table.

I use a code-based approach to create tables, and I made sure that the column is not null, but it still doesn't work. 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); } 
+7
source share
1 answer

Came to this, looking for something else, a little late, but it perfectly displays the complex 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.

+24
source

All Articles