views:

32

answers:

2

I am using EF 4.0 and in my entity data model I have several relationships where I have a 1-to-many associations and have the assocation flagged as Cascade OnDelete. Is there a way to programatically identify these associations for an entity type T?

One option I thought of was identifying these associations and in my T4 template annotate the navigation properties identifying that they are cascade delete. Of course, I would need to know how to identify if an association is flagged as Cascade Delete in my T4 template.

+2  A: 

You can programatically discover more than you ever wanted to know about your entity model via the MetadataWorkspace class. The API is a bit of a challenge to figure out, however. Here is an example of how to discover relationships (via navigation properties) and their associated OnDelete setting:

using (var context = new AppEntities())
{
    var container = context.MetadataWorkspace.GetEntityContainer("AppEntities", System.Data.Metadata.Edm.DataSpace.CSpace);

    foreach (var entitySet in container.BaseEntitySets.OfType<EntitySet>())
    {
        var elementType = entitySet.ElementType;

        foreach (var np in elementType.NavigationProperties)
        {
            if (np.FromEndMember.DeleteBehavior == OperationAction.Cascade)
            {
                var entityType = np.FromEndMember.GetEntityType();

                // do stuff...
            }

            if (np.ToEndMember.DeleteBehavior == OperationAction.Cascade)
            {
                var entityType = np.ToEndMember.GetEntityType();

                // do stuff...
            }
        }
    }
}

Just FYI, I think the above code may identify the same relationship twice (once from each end).

Daniel Pratt
A: 

Daniel's answer will work the same as this, but I am providing an alternate solution. I did some digging and found you can do this check in your T4 template for your POCO's:

// Iterates the Navigation properties for the entity
foreach (NavigationProperty navProperty in entity.NavigationProperties.Where(np => np.DeclaringType == entity))

// Checks if the navigation property is Cascade Delete.
if (ef.IsCascadeDeletePrincipal(navProperty))

I was able to add an annotation within the check that contained all of the information I needed to know.

Programatically, I would follow Daniel's example, but for templating, my example will identify the cascade delete associations.

Brandon