Victor
Victor

Reputation: 297

enumerate entity children

I need to create a method that will take Linq-to-sql entity and return a list of all it's children(only 1st generation) entitysets, without any data that entitysets contain, just names. Is there any way I can do that? Thanks

Upvotes: 1

Views: 295

Answers (1)

Sam
Sam

Reputation: 6265

Well, if I understand your question correctly, you can inspect the meta-model for a data context instance. The meta-model describes the tables, columns and associations in your model. Basically you want to look at associations on a table where the association is 1-to-many.

This doesn't involve retrieving any data, as you are not actually working with entity instances, just the information that describes them.

This code should do it:

public static string[] GetChildEntities<T>(DataContext context, T entity)
{
   var mapping = context.Mapping.GetTable(typeof(T));
   return mapping.RowType.Associations.Where(a => a.IsMany)
                                      .Select(a => a.ThisMember.Name).ToArray();
}

This will return the names of any properties that expose the EntitySet instances for the given parent entity.

EDIT

This code finds the first 1->* association between the parent and child entities based on the meta-model, retrieves the value of the EntitySet property on the parent entity, and adds the child entity to that set. This should work for most basic LINQ to SQL implementations.

public static void AddChild<P, C>(DataContext context, P parent, C child) 
    where P : class
    where C : class
{
    var parentMapping = context.Mapping.GetTable(typeof(P));
    var childAssociation = 
             parentMapping.RowType.Associations
                     .Where(a => a.IsMany && a.OtherType.Type == typeof(C))
                     .FirstOrDefault();

    if (childAssociation != null)
    {
        var entitySet = (EntitySet<C>) childAssociation.ThisMember
                                                       .MemberAccessor
                                                       .GetBoxedValue(parent);
        entitySet.Add(child);
    }   
}

Upvotes: 1

Related Questions