开发者

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 entityset开发者_JS百科s contain, just names. Is there any way I can do that? Thanks


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜