4

I want to find all the foreign keys of an entity in my entity model.

I have used the following to get a list of all the properties for an entity:

var workspace = _entities.MetadataWorkspace; 
var entityType = workspace.GetItems<EntityType>(DataSpace.CSpace).FirstOrDefault(e => e.Name == tablename);
var keyNames = entityType.Members.Select(k => k.Name);

Is there any way to find only those properties which have foreign key associations? And also that property in the reference entity with which it is associated?

Andrey Agibalov
  • 7,624
  • 8
  • 66
  • 111
gunnerz
  • 1,898
  • 5
  • 24
  • 39

1 Answers1

8

I worked out the solution:

var fk = _entities.MetadataWorkspace
    .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 == tablename)
    .Where(x => x.ReferentialConstraints[0].ToProperties[0].Name == columnname);

// Get the corresponding reference entity column name
var refcol = fkname
    .Select(x => x.ReferentialConstraints[0].FromProperties[0].Name)
    .First();
CarenRose
  • 1,266
  • 1
  • 12
  • 24
gunnerz
  • 1,898
  • 5
  • 24
  • 39
  • 1
    I would love to upvote this. But I cannot figure out how to use it. It would be helpful to include "using" statements and (holy war alert) .. to not use "var" for learning/teaching examples. PackageReference name and version would be helpful as well. – granadaCoder Apr 01 '22 at 12:54