Mapping EF Foreign key with different names

Viewed 288

I have the below domain classes:

public class Product
{
  public Guid? Id { get; set; }
  public string? Name { get; set; }
}

public class Order
{
  public Guid? Id { get; set; }
  public string? Address{ get; set; }
  public Guid? ProductId{ get; set; }
}

I am not using navigation properties for setting the foreign key but am doing it as below:

    public void Configure(EntityTypeBuilder<Order> builder)
    {
        builder.HasOne<Product>()
               .WithMany()
               .HasForeignKey(c => c.ProductId);
    }

My problem when I do the update-database, it says that the field ProductId does not exist. This is because it named as Id in table product but in table order it is named as ProductId. Is there a way to map the foreign key with a different name?

1 Answers

Modify the Product class

public class Product
{
  public Guid? Id { get; set; }
  public string? Name { get; set; }

  public ICollection<Order> Orders {get; set;}
}

The relationship will work properly.

Reference: Relationships

Related