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?