none
Are Data Annotation allow to define compost key per model ? RRS feed

  • Question

  • 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


    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; }
        }
    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 ?
    Thursday, January 17, 2019 12:28 AM

Answers

  • Hi engahmedbarbary,

    >>Are Data Annotation allow to define compost key per model or not ?

    From the following document, we know:

    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.

    https://github.com/aspnet/EntityFramework.Docs/blob/live/entity-framework/core/modeling/keys.md#fluent-api

    >>what i do ?

    Please try fluent API like this:

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

    Best regards,

    Zhanglong




    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Thursday, January 17, 2019 2:57 AM
    Moderator