Mapping foreign key to non primary surrogate key column in EF code first

c# ef-code-first entity-framework entity-framework-6 foreign-keys

Popular Answer

I believe the best way to accomplish it is to perform it in EF code first, using either attributes or fluent api:

However, I can suggest that you slightly modify your approach – don't put a primary key onB(BName, Aid) - Create a distinct index. 38 zzz, zzz, zzz.

public class B
{    
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]     
    public virtual int Bid { get; set; }

    [Index("IX_B_Name_Aid", 1, IsUnique = true)]
    [Required]           
    Public virtual string BName {get ; set}

    [Index("IX_B_Name_Aid", 2, IsUnique = true)]
    [Required]      
    public virtual int Aid { get; set; }

    [ForeignKey("Aid")]
    public virtual  A A { get; set; }

    public virtual ICollection<C> C { get; set; }    
}


public class C
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]     
    public virtual int Cid { get; set; }

    [Key]
    [Column(Order = 0)]
    [Required]    
    Public virtual string CName {get ; set}    

    [Key]
    [Column(Order = 1)]
    [Required]          
    public virtual int Bid { get; set; }

    [ForeignKey("Bid")]
    public virtual  B B { get; set; } 
}

The index will provide you with the same query speed advantages as the main key, but with a little amount of cost to support the primary surrogate index over the secondary.Bid column).

Additionally, reading is advised: Business versus natural or surrogate keys.

4
5/23/2017 11:54:01 AM


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