Yair Nevet
Yair Nevet

Reputation: 13003

Check if entity has references in other entities in Code First

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,

Upvotes: 4

Views: 2617

Answers (1)

Douglas
Douglas

Reputation: 54887

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);
}

Upvotes: 1

Related Questions