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);
}
Entity Framework Core supports composite keys - primary key values generated from two or more fields in the database. Composite keys are not covered by conventions or data annotation attributes. The only way to configure composite keys is to use the HasKey method.
Configuring a primary key By convention, a property named Id or <type name>Id will be configured as the primary key of an entity. Owned entity types use different rules to define keys. You can configure a single property to be the primary key of an entity as follows: Data Annotations.
A composite primary key, also called a composite key, is a combination of two or more columns to form a primary key for a table. In JPA, we have two options to define the composite keys: the @IdClass and @EmbeddedId annotations.
Use the ColumnAttribute or the HasKey method to specify an order for composite primary keys. In order to use composite keys, Entity Framework requires you to define an order for the key properties. You can do this by using the Column annotation to specify an order.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With