EF one to one or zero relationship with custom foreign key column name

entity-framework-6

Question

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   |
+====+=============+==========+

1
0
5/20/2016 3:50:09 AM

Popular Answer

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; }
}

UPDATE

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.

0
5/20/2016 7:56:10 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow