1

How can I create a foreign key with Entity Framework code-first?

I need a table post to have a column userId as a foreign key.

1 Answer 1

3

With the following property attribute [ForeignKey("Column Name")]. Typically you would assign a foreign key on a navigational property not the foreign key column.

Example

public class Employee { public int Employee Id { get; set; } public int ManagerId { get; set; } public string FirstName { get; set; } public string LastName { get; set; } [ForeignKey("ManagerId")] public virtual Employee Manager { get; set; } } 
Sign up to request clarification or add additional context in comments.

2 Comments

if i'm inserting an Employee, would inserting a new manager row when the ManagerId is 0 be the expected behaviour? I guess I'll need a FK constraint..
Entity Framework will recognize the "ManagerId" column as the primary key and define it as an auto-increment primary key field within SQL Server. Check out Getting Started with Entity Framework 6 Code First using MVC 5 for a complete tutorial on getting started which demonstrates this, and much more, with details.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.