How to get a list of all Entity relation in Entity Framework 6.1?
<p>I am trying to get a list of all relations "foreign keys" on a model programmatically (key, related object, foreign column name.)</p>

<p>I found <a href="https://stackoverflow.com/questions/10817289/entity-framework-finding-foreign-keys">this other question</a> which seems to be doing the same thing. But I am unable to get the code in the answer to work for me. </p>

<p>Here is what I have done</p>

<pre><code>    public List&lt;string&gt; 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&lt;AssociationType&gt;(DataSpace.CSpace).Where(a =&gt; a.IsForeignKey);

        //check if the table has any foreign constraints for that column
        var fkname = fk.Where(x =&gt; x.ReferentialConstraints[0].ToRole.Name == type.Name).Where(x =&gt; x.ReferentialConstraints[0].ToProperties[0].Name == type.Name);

        //Get the corresponding reference entity column name
        return fkname.Select(x =&gt; x.ReferentialConstraints[0].FromProperties[0].Name).ToList();

    }
</code></pre>

<p>Here is how I call this method </p>

<pre><code>var relations = QueryExtractor.GetObjectRelations(typeof(TSource)); 
</code></pre>

<p>But this code is not working for me. The return value is empty.</p>

<p>How can I correctly get the foreign key and the object that they are are related to?</p>

<p><strong>UPDATED</strong></p>

<p>Here is my current code based on muratgu answer below. But it is still now giving me a list of the relations</p>

<pre><code>    public List&lt;Dictionary&lt;string, object&gt;&gt; GetObjectRelations(Type type)
    {
        var relations = new List&lt;Dictionary&lt;string, object&gt;&gt;();

        var metadata = ((IObjectContextAdapter)this.context).ObjectContext.MetadataWorkspace;

        var fk_all = metadata.GetItems&lt;AssociationType&gt;(DataSpace.CSpace).Where(a =&gt; a.IsForeignKey);

        var fk_out = fk_all.Where(x =&gt; x.ReferentialConstraints[0].ToRole.Name == type.Name).ToList(); // relations going out 

        foreach (var fk in fk_out)
        {
            var relation = new Dictionary&lt;string, object&gt;();

            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;
    }
</code></pre>