R Davies
R Davies

Reputation: 115

Entity Framework Reverse Navigation

I have 2 simple tables Order and Order Type.

I want to know if there is a way to reverse navigate the entity, where I can select the ordertype entity and show all orders entities.

Upvotes: 1

Views: 1521

Answers (1)

juunas
juunas

Reputation: 58898

Yes. I assume an order has one order type.

public class Order
{
    public virtual OrderType Type { get; set; }
}

public class OrderType
{
    public virtual ICollection<Order> Orders { get; set; }
}

I made the navigation properties virtual to enable lazy loading. If you want to, you can also add the foreign key property: (assuming you use a long key)

public class Order
{
    [ForeignKey("Type")]
    public long TypeId{ get; set; } //Can also be nullable (long?) if you want
    public virtual OrderType Type { get; set; }
}

public class OrderType
{
    [Key]
    public long Id { get; set; }
    public virtual ICollection<Order> Orders { get; set; }
}

Upvotes: 2

Related Questions