Sachin Kainth
Sachin Kainth

Reputation: 46760

Is it possible to have an inverse navigation property in entity framework?

I have these two entities, to which I have added the marked property that gives me an error (the error being: Unable to determine the principal end of an association between the types ...)

public class Lot
{
   [Key]
   public int Id { get; set; }

   public int Vehicle_Id { get; set; }

   [ForeignKey("Vehicle_Id")]
   public virtual Vehicle Vehicle { get; set; }
}

and

public class Vehicle
{
   public int Id { get; set; }
   public virtual Lot Lot { get; set; } // * This is the property that I added
}

A Vehicle may or may not belong in a Lot, but a Lot will always have 1 Vehicle.

I needed an inverse navigation property between these two entities from the Vehicle class such that if there is a Lot associated with a Vehicle then I can access that Lot from the Vehicle.

Is this even possible and if so how do I do it without any error?

Upvotes: 2

Views: 2149

Answers (3)

user743382
user743382

Reputation:

No, Entity Framework does not support this. Entity Framework requires tables in a zero-to-one/one-to-one relationship to share the primary key. You've got separate lot ID and vehicle IDs, so the best you can do is map this as

public class Vehicle
{
  public int Id { get; set; }
  public virtual ICollection<Lot> Lots { get; set; }
}

and then access vehicle.Lots.SingleOrDefault(). This lets EF treat it as a one-to-many relationship, but you know that "many" will never be more than one.

Upvotes: 2

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236318

Use following mapping:

modelBuilder.Entity<Lot>()
    .HasRequired(l => l.Vehicle) //  Lot will always have 1 Vehicle
    .WithOptional(v => v.Lot); // A Vehicle may or may not belong in a Lot

Upvotes: 2

Maris
Maris

Reputation: 4776

I would recommend you to write mappings by the hands instead using the fluent api:

public class LotMapping : EntityTypeConfiguration<Lot>
{
    public LotMapping()
    {
        HasKey(e => e.Id);
        // This will make the foreign key in the `Vehicle` table
        HasRequired(e=>e.Vehicle).WithRequiredPrincipal(e=>e.Lot)

        // This will make the foreign key in the `Lot` table
        HasRequired(e=>e.Vehicle).WithRequiredDependent(e=>e.Lot)
        //....
    }
}

And add to your Context this method:

protected override void OnModelCreating(DbModelBuilder modelBuilder) 
    {
        // Mappings Definitions
    modelBuilder.Configurations.Add(new LotMapping ());
    }

Hope it helps.

Upvotes: 1

Related Questions