Search code examples
c#entity-frameworkentity-data-model

API to query your Entity Framework context's model?


I'm using EF code-first, and I'd like to identify, programatically, which properties are navigation properties, which are foreign keys, and which are Ids. Eg, in this classic Order/Item example;

public class Order
{
    public int Id { get; set; }
    public virtual ICollection<OrderItem> Items { get; set;
}

public class OrderItem
{
    public int Id { get; set; }
    public int OrderId { get; set; }
    public Order Order { get; set; }
    public int ProductCount { get; set; }
}

As a programmer it's clear to me what's going on; OrderItem.OrderId is my foreign key, OrderItem.Order is a navigation property, and Order.Items is the inverse of that navgation property. It's also clear that EF knows this, because it's gone though the model-building stage

However, I'd like to be able to do this programatically; so I'm hoping there is an API, maybe with a similar feel to Reflection, which might allow me to ask questions like;

 var model = CreateModelFor(salesContext);
 var foreignKeys = model.ForeignKeysFor(typeof(Order)); // ["OrderId"]
 var navigationProperties = model.NavigationPropertiesFor(typeof(Order)) // [`Order`]

Does such a thing exist in EF?


Solution

  • You need to drop down to ObjectContext and then you can get all the information about the model by exploring MetadataWorkspace. This API and the entire model behind it is quite scary (with navigation properties being the most complicated).

    This thread contains an example that will help you get started: entity framework check if property is navigation property