Pickeroll
Pickeroll

Reputation: 978

Entity Framework - Foreign Key name

I'm having some problems in creating a Foreign Key with a code first approach.

This is my UserTable

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

    //NAVIGATION PROPERTY
    public virtual ICollection<AuctionTable> Auctions { get; set; }

}

And this is my AuctionTable

public class AuctionTable
{
        //AUCTION ID
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        [Key]
        public int AuctionId { get; set; }

        //NAVIGATION PROPERTY
        public string Seller { get; set; }
        public virtual UserTable Users{ get; set; }
}

Seller should my FK but the program seems to recognize it only if I rename it as "Username" (the primary key of the other table).

I've tried using the foreign key tag [ForeignKey("UserTable")] over Seller, but it didn't work.

Do you have any advice?

Upvotes: 0

Views: 972

Answers (2)

ocuenca
ocuenca

Reputation: 39326

Code First has a set or rules it applies to try and locate a foreign key property when it discovers a relationship. The rules are based on the name of the property. The foreign key property will be discovered by convention if it is named [Target Type Key Name], [Target Type Name] + [Target Type Key Name], or [Navigation Property Name] + [Target Type Key Name]. The Seller property you added not matched with any of these three rules. Adding ForeignKey attribute to the Seller FK property, along with information telling it which navigation property represents the relationship it is a foreign key for, will fix the problem:

public class AuctionTable
{
    [Key]
    public int AuctionId { get; set; }

    [ForeignKey("User")]
    public string Seller { get; set; }

    public virtual UserTable User { get; set; }
}

Alternatively, you can apply the ForeignKey annotation to the navigation property ( as @Andy shows in his answer) and tell it which property is the foreign key for the relationship.

Upvotes: 1

LesterMac
LesterMac

Reputation: 346

make this your AuctionTable:

public class AuctionTable
{
    //AUCTION ID
    [Key]
    public int AuctionId { get; set; }

    //NAVIGATION PROPERTY
    public string Seller { get; set; }
    [ForeignKey("Seller")]
    public virtual UserTable Users { get; set; }
}

Upvotes: 1

Related Questions