Is Cascade enabled for DbSet?

Using the Entity Framework, how do you know if the "Delete Cascade" option is enabled for a table before deleting any records from it?

public partial class DataContext : DbContext { public DbSet<Building> Buildings { get; set; } public DbSet<Room> Rooms { get; set; } } DataContext context; Building building; // Will this start a DELETE CASCADE, removing Rooms within the Building? context.Buildings.Remove(building); 

This is for a general function, so I can use DbSet <T> or DbContext, but not T.
You must run the test at run time before calling Remove ().

You can detect DELETE CASCADE before executing the deletion, and if so, how?

+7
generics c # sql entity-framework
source share
2 answers

You can easily use a t-sql function or query that gives you the information you are using. Try wrapping the following with any predicates you want (for example, WHERE PK.TABLE_NAME = 'My Table' AND C. DELETE_RULE = 'CASCADE'. If the record a exists, then you have the necessary information.

 SELECT FK_TableName = FK.TABLE_SCHEMA + '.' + FK.TABLE_NAME, FK_ColumnName = CU.COLUMN_NAME, PK_TableName = PK.TABLE_SCHEMA + '.' + PK.TABLE_NAME, PK_ColumnName = PT.COLUMN_NAME, ConstraintName = C.CONSTRAINT_NAME, DeleteRule = C.DELETE_RULE FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS C INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS FK ON C.CONSTRAINT_NAME = FK.CONSTRAINT_NAME INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS PK ON C.UNIQUE_CONSTRAINT_NAME = PK.CONSTRAINT_NAME INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE CU ON C.CONSTRAINT_NAME = CU.CONSTRAINT_NAME INNER JOIN ( SELECT i1.TABLE_NAME, i2.COLUMN_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS i1 INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE i2 ON i1.CONSTRAINT_NAME = i2.CONSTRAINT_NAME WHERE i1.CONSTRAINT_TYPE = 'PRIMARY KEY' ) PT ON PT.TABLE_NAME = PK.TABLE_NAME; 

You can then wrap this in a DbSet extension and call it as context.Set<MyEntity>().UsesCascadeDelete() , which launches the above query with your predicates and everything else that you want.

Since EF can easily run TSQL queries, I would still consider them to be a β€œpart” of EF.

+1
source share

Will read FK metadata or verify entity to use FK ? There seem to be several ways to try, although I have not tried either.

I usually check manually the mapping files and code repositories based on this knowledge. Perhaps the previous Stackoverflow answers will allow you to create something more general if you need to.

+1
source share

All Articles