You can define foreign key by:
public class Parent
{
public int Id { get; set; }
public virtual ICollection<Child> Childs { get; set; }
}
public class Child
{
public int Id { get; set; }
// This will be recognized as FK by NavigationPropertyNameForeignKeyDiscoveryConvention
public int ParentId { get; set; }
public virtual Parent Parent { get; set; }
}
Now ParentId is foreign key property and defines required relation between child and existing parent. Saving the child without exsiting parent will throw exception.
If your FK property name doesn't consists of the navigation property name and parent PK name you must either use ForeignKeyAttribute data annotation or fluent API to map the relation
Data annotation:
// The name of related navigation property
[ForeignKey("Parent")]
public int ParentId { get; set; }
Fluent API:
modelBuilder.Entity<Child>()
.HasRequired(c => c.Parent)
.WithMany(p => p.Childs)
.HasForeignKey(c => c.ParentId);
Other types of constraints can be enforced by data annotations and model validation.
Edit:
You will get an exception if you don't set ParentId
. It is required property (not nullable). If you just don't set it it will most probably try to send default value to the database. Default value is 0 so if you don't have customer with Id = 0 you will get an exception.