Click here to Skip to main content
15,889,992 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Problem

i work on asp.net core 2.1 visual studio 2017 code first with repository pattern

when do create database i do as following

Add-Migration InitialCreate

but i got error

Entity type 'Employee' has composite primary key defined with data annotations. To set composite primary key, use fluent API.

and Employee Model as below


Are Data Annotation allow to define compost key per model or not ?
I need to Create Employee Table with compost key EmployeeId , BranchCode

what i do ?

What I have tried:

public class Employee
    {
        [Key]
        [Column(Order = 1)]
        public int EmployeeId { get; set; }
        [Key]
        [Column(Order = 2)]
        public int BranchCode { get; set; }
        public string EmployeeName { get; set; }
        public int EmployeeAge { get; set; }
        public DateTime JoinDate { get; set; }
        public DateTime BirthDate { get; set; }
        public bool Active { get; set; }
    }
Posted
Updated 18-Jan-19 3:32am

1 solution

No:
Composite keys can only be configured using the Fluent API - conventions will never setup a composite key and you can not use Data Annotations to configure one.

You have to use the fluent API to set up a composite key.
C#
class MyContext : DbContext
{
    public DbSet<Car> Cars { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Employee>()
            .HasKey(e => new { e.EmployeeId, e.BranchCode });
    }
}

There is an open request to add support for creating composite keys using data annotations:
KeyAttribute support for composite primary key · Issue #11003 · aspnet/EntityFrameworkCore · GitHub[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900