How do i make the foreign key column to have a custom name. by default EF will append "_" to the foreign key column
Customer
POCO:
public class Customer
{
public int Id { get; set; }
public string Name { get; set; }
public virtual Order Order { get; set; }
}
EF Config:
HasKey(m => m.Id);
HasOptional(m => m.Order).WithOptionalPrincipal(e => e.Customer);
Customer table:
+====+=======+
| Id | Name |
+====+=======+
| 1 | Cust1 |
+----+-------+
| 2 | Cust2 |
+----+-------+
| 3 | Cust3 |
+----+-------+
| 4 | Cust4 |
+----+-------+
| 5 | Cust5 |
+====+=======+
Order
POCO:
public class Order
{
public int Id { get; set; }
public string ItemName { get; set; }
public virtual Customer Customer { get; set; }
}
EF Config:
HasKey(m => m.Id);
Order table:
+====+=============+==========+
| Id | Customer_Id | ItemName |
+====+=============+==========+
| 1 | 2 | Modem |
+----+-------------+----------+
| 2 | 5 | Router |
+====+=============+==========+
How can i make the Order table as follow (to have "CustomerId" as the actual property name)?
+====+=============+==========+
| Id | CustomerId | ItemName |
+====+=============+==========+
| 1 | 2 | Modem |
+----+-------------+----------+
| 2 | 5 | Router |
+====+=============+==========+
I usually use the attributes to define my mapping to SQL directly on the entities (but I can see plenty of reasons why one wouldn't do that). Anyway, here is how to do it using attributes:
public class Order
{
[Key]
public int Id { get; set; }
[Column]
public string ItemName { get; set; }
[Column]
public int? CustomerId { get; set; }
[ForeignKey("CustomerId")]
public virtual Customer Customer { get; set; }
}
Something like
HasKey(m => m.Id);
HasOptional(m => m.Order)
.WithOptionalPrincipal(e => e.Customer)
.Map(m => m.MapKey("CustomerId"));
might do if you don't want to use attributes.