EF6 Foreign Key Issue

entity-framework entity-framework-6

Question

Here are my models

public class Driver
{
    public int Id { get; set; }
    public String Name { get; set; }
    public int VehicleId { get; set; }
    public virtual Vehicle Vehicle  { get; set; }
}

public class Vehicle
{  
    public int Id { get; set; }
    public String Name { get; set; }

    public virtual Driver Driver { get; set; }

    public int VehicleGroupId { get; set; }
    public virtual VehicleGroup Vehicles { get; set; }
}

I'm getting the following error on updating database:

Unable to determine the principal end of an association between the types 'AppName.Models.Vehicle' and 'AppName.Models.Driver'. The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations.

I wish to solve the issue using data annotations. I've tried putting foreign key attribute over Driver Navigation property in vehicle model. But no success. Any help is much appreciated.

Accepted Answer

To solve your problem you need to explicitly set the end of the association like this :

public class Vehicle
{  
    [Key, ForeignKey("Driver")]
    public int Id { get; set; }
    public String Name { get; set; }

    public virtual Driver Driver { get; set; }

    public int VehicleGroupId { get; set; }
    public virtual VehicleGroup Vehicles { get; set; }
}

I think your model is inccorect because a driver can use many vehicles in real life ;)




Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why