EntityFramework Class with a composite key

Issue

You have a database table with a primary key made up of two columns. This is also called a composite key.

You want to model this in your class using the DataAnnotations Attributes.

The solution

As of the later .Net Core, (I think 6 or above) you need to:

Reference the NuGet Package

    Looks something like this in your solution file

    <ItemGroup>
      <PackageReference Include="Microsoft.EntityFrameworkCore" Version="8.0.12" />
    </ItemGroup>

    Then create you class as follows

    [Table("MyTable")]
    [PrimaryKey(nameof(PKOneId), nameof(PKTwoId))]
    public class MyTableDto
    {
        public required int PKOneId { get; set; }
        public required int PKTwoId{ get; set; }
        public bool IsActive { get; set; }
    }

    Leave a Reply

    Your email address will not be published. Required fields are marked *

    This site uses Akismet to reduce spam. Learn how your comment data is processed.