How to get a list of all Entity relation in Entity Framework 6.1?

c# entity entity-framework entity-framework-6 relation

Popular Answer

You already have all the information you need in your piece of code, but I have a feeling that producing a list of strings won't be sufficient for your needs. I'll break it down so you can choose how to use the information.

        // assume Child has a foreign key (Parent_Id) to Parent (Id)
        // assume primary keys are not composite
        var type = typeof(Child); 
        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) { // could be many
            var fk_ref = fk.ReferentialConstraints[0]; // what if more than one?
            Console.WriteLine("From {0} - {1} ", fk_ref.FromRole.Name, fk_ref.FromProperties[0].Name);
            Console.WriteLine("To {0} - {1} ", fk_ref.ToRole.Name, fk_ref.ToProperties[0].Name);
        }

Assuming Child own a foreign key.Parent_Id to Parent (Id the following will print:

        From Parent - Id
        To Child - Parent_Id
1
6/29/2016 12:52:37 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow