I am trying to get a list of all relations "foreign keys" on a model programmatically (key, related object, foreign column name.)
I found this other question which seems to be doing the same thing. But I am unable to get the code in the answer to work for me.
Here is what I have done
public List<string> GetObjectRelations(Type type)
{
var metadata = ((IObjectContextAdapter)this.context).ObjectContext.MetadataWorkspace;
// Get the part of the model that contains info about the actual CLR types
var objectItemCollection = ((ObjectItemCollection)metadata.GetItemCollection(DataSpace.OSpace));
var fk = metadata.GetItems<AssociationType>(DataSpace.CSpace).Where(a => a.IsForeignKey);
//check if the table has any foreign constraints for that column
var fkname = fk.Where(x => x.ReferentialConstraints[0].ToRole.Name == type.Name).Where(x => x.ReferentialConstraints[0].ToProperties[0].Name == type.Name);
//Get the corresponding reference entity column name
return fkname.Select(x => x.ReferentialConstraints[0].FromProperties[0].Name).ToList();
}
Here is how I call this method
var relations = QueryExtractor.GetObjectRelations(typeof(TSource));
But this code is not working for me. The return value is empty.
How can I correctly get the foreign key and the object that they are are related to?
UPDATED
Here is my current code based on muratgu answer below. But it is still now giving me a list of the relations
public List<Dictionary<string, object>> GetObjectRelations(Type type)
{
var relations = new List<Dictionary<string, object>>();
var metadata = ((IObjectContextAdapter)this.context).ObjectContext.MetadataWorkspace;
var fk_all = metadata.GetItems<AssociationType>(DataSpace.CSpace).Where(a => a.IsForeignKey);
var fk_out = fk_all.Where(x => x.ReferentialConstraints[0].ToRole.Name == type.Name).ToList(); // relations going out
foreach (var fk in fk_out)
{
var relation = new Dictionary<string, object>();
var fk_ref = fk.ReferentialConstraints[0]; //How can a foreign key relation have more than one column?
var objectName = fk_ref.FromRole.Name;
var attributeName = fk_ref.FromProperties[0].Name;
relation.Add(objectName, attributeName);
relations.Add(relation);
}
return relations;
}