Do primary key constraints get applied to foreign keys by convention in EntityFramework Code First

StackOverflow https://stackoverflow.com/questions/23509018

Question

Suppose you defined these two entities in EntityFramework Code First.

public class Parent
{
     [MaxLength(10)]
     public string ID { get; set;}
     public virtual ICollection<Child> Children { get; set; }
}

public class Child
{
     public string ParentID { get; set; }
     public Parent Parent { get; set; } 
}

Would the MaxLength constraint be applied automatically to Child's ParentID property? Would other constraints?

If so, was it introduced in the first version of EF Code First?

I am going to go verify the first part of my question, but I couldn't find the answer on here, and it seems like people might want to know.

EDIT: Removed the Key attribute on Parent.ID

Était-ce utile?

La solution

I just tested your code and the db created does result in a MaxLength of 10 getting applied to the child's parentID property. From memory this has been in CF for as long as I have been using it- since 2011. Also you don't have to use [Key] attribute as you are following the correct convention of ID or {entity}ID for a primary key.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top