[asp.net-mvc-3] How Should I Declare Foreign Key Relationships Using Code First Entity Framework (4.1) in MVC3?

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.

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.

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.

NEW INFORMATION

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.

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

This is the error I get now when accessing the VS generated view for Patient:

ERROR MESSAGE

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.

Regards,

Guido

This question is related to asp.net-mvc-3 ef-code-first entity-framework-4.1

The answer is


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.


Examples related to asp.net-mvc-3

Better solution without exluding fields from Binding IIs Error: Application Codebehind=“Global.asax.cs” Inherits=“nadeem.MvcApplication” Can we pass model as a parameter in RedirectToAction? return error message with actionResult Why is this error, 'Sequence contains no elements', happening? Failed to load resource: the server responded with a status of 500 (Internal Server Error) in Bind function 500.19 - Internal Server Error - The requested page cannot be accessed because the related configuration data for the page is invalid String MinLength and MaxLength validation don't work (asp.net mvc) How to set the value of a hidden field from a controller in mvc How to set a CheckBox by default Checked in ASP.Net MVC

Examples related to ef-code-first

EntityType 'IdentityUserLogin' has no key defined. Define the key for this EntityType There is already an object named in the database The entity type <type> is not part of the model for the current context Entity Framework 6 Code first Default value Unique Key constraints for multiple columns in Entity Framework Entity Framework (EF) Code First Cascade Delete for One-to-Zero-or-One relationship Introducing FOREIGN KEY constraint may cause cycles or multiple cascade paths - why? How to delete and recreate from scratch an existing EF Code First database Entity Framework: One Database, Multiple DbContexts. Is this a bad idea? Ignoring a class property in Entity Framework 4.1 Code First

Examples related to entity-framework-4.1

Entity Framework Join 3 Tables How to include a child object's child object in Entity Framework 5 Ignoring a class property in Entity Framework 4.1 Code First The type or namespace name 'Entity' does not exist in the namespace 'System.Data' Validation failed for one or more entities. See 'EntityValidationErrors' property for more details StringLength vs MaxLength attributes ASP.NET MVC with Entity Framework EF Code First Entity framework code-first null foreign key How do I detach objects in Entity Framework Code First? Entity Framework Code First - two Foreign Keys from same table How Should I Declare Foreign Key Relationships Using Code First Entity Framework (4.1) in MVC3?