Pickeroll
Pickeroll

Reputation: 978

Both FK and primary key - Entity Framework

I have two tables. I would like to declare SiteId (along with Username) as the primary key.

Approaches like [Key] or [Key,ForeignKey("SiteId)] didn't work well.

public class SiteTable
{
    //SITE ID
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [Key]
    public int SiteId { get; set; }

    // NAVIGATION PROPERTY 
    public virtual ICollection<UserTable> Users { get; set; }
}

public class UserTable
{
    //USERNAME
    [Key]
    public string Username { get; set; }

    //FK
    public int SiteId { get; set; }

    //NAVIGATION PROPERTY        
    public virtual SiteTable Sites { get; set; }
}

Upvotes: 0

Views: 35

Answers (1)

ivamax9
ivamax9

Reputation: 2629

Try to define your composite key like that:

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

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

   public virtual SiteTable Site { get; set; }
}

Upvotes: 1

Related Questions