Mapping composite keys using EF code first

Sql server table:

SomeId PK varchar(50) not null 
OtherId PK int not null

How should I map this in EF 6 code first?

  • SQL Server Optimization: better to use “NOT NULL” or “>0”?
  • Spring JDBC “IF NOT EXIST INSERT” Primary key constraint violation
  • Insert statement with sub queries
  • Using SQL Server Users and Roles as an authorization database for an intranet web application?
  • Temporarily disable all foreign key constraints
  • SQL - Select Boolean Results from Table
  • public class MyTable
    {
        [Key]
        public string SomeId { get; set; }
    
        [Key]
        public int OtherId { get; set; }
    }
    

    I’ve seen some examples where you have to set the order for each column, is that required?

    Is there official documentation on this somewhere?

  • Linq EF group by to get latest entries into list of objects
  • Calling Update Procedure in WPF?
  • C# Alter Table and Add a column programmatically ASP.Net & SQL Server
  • The model backing the 'EmployeeDetailsContext' context has changed since the database was created.
  • How do I add a record only if it doesn't already exist in SQL Server?
  • Database changes not propagating to entity model
  • 3 Solutions collect form web for “Mapping composite keys using EF code first”

    You definitely need to put in the column order, otherwise how is SQL Server supposed to know which one goes first? Here’s what you would need to do in your code:

    public class MyTable
    {
      [Key, Column(Order = 0)]
      public string SomeId { get; set; }
    
      [Key, Column(Order = 1)]
      public int OtherId { get; set; }
    }
    

    You can also look at this SO question. If you want official documentation, I would recommend looking at the official EF website. Hope this helps.

    EDIT: I just found a blog post from Julie Lerman with links to all kinds of EF 6 goodness. You can find whatever you need here.

    Through Configuration, you can do this:

    Model1
    {
        int fk_one,
        int fk_two
    }
    
    Model2
    {
        int pk_one,
        int pk_two,
    }
    

    then in the context config

    public class MyContext : DbContext
    {
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Model1>()
                .HasRequired(e => e.Model2)
                .WithMany(e => e.Model1s)
                .HasForeignKey(e => new { e.fk_one, e.fk_two })
                .WillCascadeOnDelete(false);
        }
    }
    

    For Mapping Composite primary key using Entity framework we can use two approaches.

    1) By Overriding the OnModelCreating() Method

    For ex: I have the model class named VehicleFeature as shown below.

    public class VehicleFeature
    {
        public int VehicleId { get; set; }
        public int FeatureId{get;set;}
        public Vehicle Vehicle{get;set;}
        public Feature Feature{get;set;}
    }
    

    The Code in my DBContext would be like ,

    public class VegaDbContext : DbContext
    {
        public DbSet<Make> Makes{get;set;}
    
        public DbSet<Feature> Features{get;set;}
        public VegaDbContext(DbContextOptions<VegaDbContext> options):base(options)        
        {           
    
        }
        // we override the OnModelCreating method here.
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<VehicleFeature>().HasKey(vf=> new {vf.VehicleId, vf.FeatureId});
        }
    }
    

    2) By Data Annotations.

    public class VehicleFeature
    {
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]  
        [Key]
        public int VehicleId { get; set; }
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]   
        [Key]
        public int FeatureId{get;set;}
        public Vehicle Vehicle{get;set;}
        public Feature Feature{get;set;}
    }
    

    Please refer the below links for the more information.

    1) https://msdn.microsoft.com/en-us/library/jj591617(v=vs.113).aspx

    2) How to add a composite unique key using EF 6 Fluent Api?

    MS SQL Server is a Microsoft SQL Database product, include sql server standard, sql server management studio, sql server express and so on.