0

I try to get collection of FKs of entity from edmx file. I cannot find a method or property which return collection or only bool property to indicate the property of entity is FK. I searched EntityContainer class in MetadataProperties and finded nothing. I searched in class Type in property GetProperties and same result, I cannot find method or property to indicate FK. How I get FK or indication of FK of entity from edmx file?

Sorry my bad english.

Thanks

Pimpy
  • 49
  • 1
  • 1
  • 10
  • Hi, show to us the model, and what you have tried – Jorge Feb 10 '14 at 12:09
  • DO you need the value of the property? – Oliver Feb 10 '14 at 12:10
  • Model has over 10 thousend lines. I thing its not good to paste it here. I dont need the value, only some indication the property is foreign key. I search in EntityContainer.BaseEntitySets in assosiacations sets and in entity sets and in class typeof(Entity).Properties(). – Pimpy Feb 10 '14 at 12:12

2 Answers2

0

You can get the Foriegn Key using reflection and filtering the properties on the ForeignKeyAttribute.

public static IEnumerable<PropertyInfo> GetForeignKeyProps(Type type) {
  return type.GetProperties()
    .Where(prop => prop.IsDefined(typeof(ForeignKeyAttribute), false));
}

Usage, to get values:

var obj = new T();

var foreignKeyPropertyInfos = GetForeignKeyProps(typeof (T));
foreach (var foreignKeyPropertyInfo in foreignKeyPropertyInfos)
{
  var value = foreignKeyPropertyInfo.GetValue(obj)
}
Oliver
  • 35,233
  • 12
  • 66
  • 78
0

You are probably looking for the ObjectSet (from older EF) which gives you access to the navigation properties. You can get your hands on it like this:

var objectContext = ((IObjectContextAdapter)db).ObjectContext;
var os = objectContext.CreateObjectSet<TEntity>();
var foreignKeyProperties = os.EntitySet.ElementType.NavigationProperties.Where(x => x.ToEndMember.RelationshipMultiplicity == RelationshipMultiplicity.One);

db is the DBContext, TEntity is the type of the entity you are using

David Colwell
  • 2,450
  • 20
  • 31