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 2008 - create database script (schema + data) with command-line
  • Externally activate non-.NET application from Service Broker
  • Is there a scalable alternative to SQL Server Query Notifications for raising events in an application from SQL Server?
  • TSQL - Partition BY if in order
  • Return value from exec(@sql)
  • Finding someone's age in SQL
  • 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?

  • Any way to SQLBulkCopy “insert or update if exists”?
  • SQL: Update a row and returning a column value with 1 query
  • How can I populate a class from the results of an SQL query in C#?
  • SqlBulkCopy Insert with Identity Column
  • INSERT INTO if not exists SQL server
  • What is the equivalent of bigint in C#?
  • 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.