title: How Should I Declare Foreign Key Relationships Using Code First Entity Framework (4.1) in MVC3?
body: <p>I have been searching for resources on how to declare foreign key relationships and other constraints using code first EF 4.1 without much luck. Basically I am building the data model in code and using MVC3 to query that model. Everything works via MVC which is great (kudos to Microsoft!) but now I want it NOT to work because I need to have data model constraints. </p>
  
  <p>For example, I have a Order object that has a ton of properties that are external objects (tables). Right now I can create an Order no problem, but without being able to add the foreign key or external objects. MVC3 sets this up no problem. </p>
  
  <p>I realize that I could just add the objects myself in the controller class prior to save, but I would like the call to DbContext.SaveChanges() to fail if the constraint relationships have not been met.</p>
  
  <blockquote>
    <p>NEW INFORMATION</p>
    
    <p>So, specifically, I would like an
    exception to occur when I attempt to
    save an Order object without
    specifying a customer object. This
    does not seem to be the behavior if I
    just compose the objects as described
    in most Code First EF documentation. </p>
  </blockquote>
  
  <p>Latest code:</p>
  
  <pre><code>public class Order
  {
      public int Id { get; set; }
  
      [ForeignKey( "Parent" )]
      public Patient Patient { get; set; }
  
      [ForeignKey("CertificationPeriod")]
      public CertificationPeriod CertificationPeriod { get; set; }
  
      [ForeignKey("Agency")]
      public Agency Agency { get; set; }
  
      [ForeignKey("Diagnosis")]
      public Diagnosis PrimaryDiagnosis { get; set; }
  
      [ForeignKey("OrderApprovalStatus")]
      public OrderApprovalStatus ApprovalStatus { get; set; }
  
      [ForeignKey("User")]
      public User User { get; set; }
  
      [ForeignKey("User")]
      public User Submitter { get; set; }
  
      public DateTime ApprovalDate { get; set; }
      public DateTime SubmittedDate { get; set; }
      public Boolean IsDeprecated { get; set; }
  }
  </code></pre>
  
  <p>This is the error I get now when accessing the VS generated view for Patient:</p>
  
  <blockquote>
    <p>ERROR MESSAGE</p>
    
    <p>The ForeignKeyAttribute on property
    'Patient' on type
    'PhysicianPortal.Models.Order' is not
    valid. The foreign key name 'Parent'
    was not found on the dependent type
    'PhysicianPortal.Models.Order'. The
    Name value should be a comma separated
    list of foreign key property names.</p>
  </blockquote>
  
  <p>Regards,</p>
  
  <p>Guido</p>