Sitong Chen
Sitong Chen

Reputation: 21

EntityFramework Code First Adding unnecessary foreign key

I have two classes in my Pocos

public class Listing
{
    public int ListingId { get; set; }

    [ForeignKey("Seller")]
    public int SellerId { get; set; }
    public virtual User Seller { get; set; }

    [Required]
    public string ItemCategory { get; set; }

    [Required]
    public string ItemName { get; set; }

    [Required]
    public decimal Cost { get; set; }

    public DateTime DateOfPublish { get; set; }

    [Required]
    public bool SaleStatus { get; set; }

    [ForeignKey("Buyer")]
    public Nullable<int> BuyerId { get; set; }
    public virtual User Buyer { get; set; }
}

And

public class User
{
    public int UserId { get; set; }

    [Required]
    public string FirstName { get; set; }

    [Required]
    public string SecondName { get; set; }

    [Required]
    public string Email { get; set; }

    [Required]
    public string Password { get; set; }

    public string PhoneNumber { get; set; }

    public string Address { get; set; }

    public virtual ICollection<Listing> Listings { get; set; }

When I migrate this onto the database I get BuyerId, SellerId and User_UserId

The User_UserId column is totally unnecessary but I am not sure what to do with my code in order to remove it.

Upvotes: 2

Views: 72

Answers (1)

Ivan Stoev
Ivan Stoev

Reputation: 205859

Seller and Buyer navigation properties in Listing class define two many to one relationships. But there is single collection navigation property Listings in User class. Since EF does not know to which of the two relationships it should be mapped, it simply considers it being a third relationship with no corresponding reference navigation property and default by convention FK name User_UserId.

You need to map the Listings property to one of the reference navigation properties. One way to do that is by using the InverseProperty attribute. Or replace it with two collection navigation properties and map them to the corresponding reference navigation properties.

Shortly, replace

public virtual ICollection<Listing> Listings { get; set; }

with

[InverseProperty("Seller")]
public virtual ICollection<Listing> SellerListings { get; set; }
[InverseProperty("Buyer")]
public virtual ICollection<Listing> BuyerListings { get; set; }

Upvotes: 1

Related Questions