-1

We have a Country class which is added as a reference in a few other entities:

public class Country 
{
    public string Name { get; set; }
}

public class Group
{
    public string Name { get; set; }

    public int CountryId { get; set; }

    public virtual Country Country { get; set; }
}

public class User
{
    [MaxLength(50)]
    public string Name { get; set; }

    [MaxLength(10)]
    public string UserName { get; set; }

    public int CountryId { get; set; }

    public virtual Country Country { get; set; }
}

From above by using Country entity, how can we find that it is used in Group and User class? Any generic way so that we can utilize it for any entity type?

I got the code which gives used foreign key in entity

 public IEnumerable<string> GetFKPropertyNames<TEntity>() where TEntity : class
    {
        using (var context = new DataContext())
        {

            ObjectContext objectContext = ((IObjectContextAdapter)context).ObjectContext;
            ObjectSet<TEntity> set = objectContext.CreateObjectSet<TEntity>();

            var Fks = set.EntitySet.ElementType.NavigationProperties.SelectMany(n => n.GetDependentProperties());
            return Fks.Select(fk => fk.Name);
        }
    }

var result = GetFKPropertyNames<User>();

result will return "CountryId" as it used as foreign key.

Now, what we need is. If we provide Country entity it should give us User and Group as these two entities have CountryId as a foreign key .

How can we achieve this?

Oxygen
  • 831
  • 4
  • 17
  • 42

1 Answers1

0

Able to identify the way, it can be achieve as -

 public IEnumerable<string> GetReferencedEntities<TEntity>() where TEntity : class
    {
        using (var context = new DataContext())
        {

            ObjectContext objectContext = ((IObjectContextAdapter)context).ObjectContext;
            ObjectSet<TEntity> set = objectContext.CreateObjectSet<TEntity>();

            string tEntityName = typeof(TEntity).Name;

            var Fks = set.EntitySet.EntityContainer.AssociationSets.Where(r => r.Name.EndsWith(tEntityName)).ToList();

            //var Fks = set.EntitySet.ElementType.NavigationProperties.Select(n => n.DeclaringType);
            return Fks.Select(fk => fk.Name);
        }
    }
var result = GetReferencedEntities<Country>();

The result output will have Group_Country and User_Country. These are the ones in which country is being used as a foreign key.

Oxygen
  • 831
  • 4
  • 17
  • 42