Mapping composite keys using EF code first

c# entity-framework entity-framework-6 sql-server

Accepted Answer

The column order must absolutely be specified; otherwise, how is SQL Server meant to know which one comes first? You would need to include the following in your code:

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

  [Key, Column(Order = 1)]
  public int OtherId { get; set; }
}

Also available is this SO inquiry. I suggest looking at the EF's official webpage if you need formal documentation. Hope this was useful.

EDIT: I recently came upon a blog article from Julie Lerman with links to a ton of awesome EF 6 content. You can locate anything you require here.

181
5/17/2018 6:53:04 PM

Popular Answer

We have two options for mapping composite primary keys using Entity Framework.

1) 9 to zzz

For instance, as shown below, I have a model class called VehicleFeature.

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

My DBContext's code looks like this:

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) zzzz-29 zzzz

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;}
}

For more information, please click on the links below.

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

2) zzzz-49 zzzz



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow