4

Do you maybe know how can I determine whether an entity has references to it in other entities or not?

If I talk in SQL language, I mean, can I check if a Primary Key is a Foreign Key in certain tables.

I want to mark an entity object as IsDeleted(it's a property) only if it does not have any references to it from another tables, I want to avoid physically remove.

Thank you,

Yair Nevet
  • 12,725
  • 14
  • 66
  • 108
  • 1
    Do you have navigation properties to related entities. If not its time to use them and after that you will just load them from database and check if there are any objects. – Ladislav Mrnka Jan 15 '12 at 18:47

1 Answers1

1

For simple cases, you can check for the existence of foreign keys using the Any operator:

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

public class City
{
    public int ID { get; set; }
    public int CountryID { get; set; }
    public string Name { get; set; }
}

public bool IsCountryReferenced(Country country, IEnumerable<City> cities)
{
    return cities.Any(city => city.CountryID == country.ID);
}
Douglas
  • 53,759
  • 13
  • 140
  • 188
  • Hi and thanks for the example but I don't think it's a good Technic because what if many tables are related to me? what if also Customers and Shipping tables would be related to me tomorrow? think about it... – Yair Nevet Jan 15 '12 at 22:33
  • Yes, agreed. However, wouldn’t the same issue apply if you were using Transact-SQL? If you have defined foreign key constraints in your database, then SQL Server would (by default) prevent you from deleting a primary key that is still referenced; however, it does not offer you a facility to select those rows, unless you build a join query against all foreign-key tables; see [SQL: how to find unused primary key](http://stackoverflow.com/questions/5388715/sql-how-to-find-unused-primary-key). – Douglas Jan 16 '12 at 18:57