实体框架 - 如何查找导航属性的反向属性?

时间:2014-08-16 13:51:50

标签: c# entity-framework code-first

我想知道如何正确地确定另一个属性的反向导航属性。我已经成功地完成了这项工作(见下面的代码),但我不知道它是否真的正确。它似乎工作,但我现在有点担心部署此代码。

例如,我有两种对象类型:

class Paper {

  public int Id { get; set; }
  public Person Author { get; set; }
  public string Text { get; set; }
}

class Person {
  public int Id { get; set; }
  public string Name { get; set; }
  public ICollection<Paper> Papers { get; set; }
}

现在,我如何在运行时确定Person-type是否具有&#39; Papers&#39; -property(即&#39;作者&#39;)的反向属性,或者根本没有?< / p>

以下是我的代码的摘录。这是正确的方法吗?见评论。

var context = ((IObjectContextAdapter)someDbContext).ObjectContext;

// First, compile a preliminary list of relationship end members to type with navigational property.
// This list can then be used to compile a dictionary in the format of type, propertyName = type, propertyName, to determine the inverse (if any).

var relationshipEndMembers = new Dictionary<RelationshipEndMember, Tuple<EntityType, NavigationProperty>>();

foreach (var s in context.MetadataWorkspace.GetEntityContainer(context.DefaultContainerName, DataSpace.CSpace).BaseEntitySets)
{
    foreach (var m in s.ElementType.Members)
    {
        var associationEndMember = m as AssociationEndMember;

        if (associationEndMember != null)
        {
            var type = associationEndMember.GetEntityType();

            // Is this the correct way of looping through all navigation properties? s.ElementType.Members.OfType<NavigationProperty>() only resulted in a very few of my navigational properties!

            foreach (var p in type.DeclaredNavigationProperties)
            {
                if (!relationshipEndMembers.ContainsKey(p.FromEndMember))
                    relationshipEndMembers.Add(p.FromEndMember, new Tuple<EntityType, NavigationProperty>(type, p));
            }
        }
    }
}

// Compile the result

var navigationProperties = new Dictionary<Tuple<string, string>, Tuple<string, string>>();

foreach (var p in relationshipEndMembers)
{
    Tuple<EntityType, NavigationProperty> inverse;

    if (relationshipEndMembers.TryGetValue(p.Value.Item2.ToEndMember, out inverse))
        navigationProperties.Add(new Tuple<string, string>(p.Value.Item1.Name, p.Value.Item2.Name), new Tuple<string, string>(inverse.Item1.Name, inverse.Item2.Name));
}

// Now it is possible to query the navigationProperties with a type and property as the key, to obtain (if any) the inverse type and property

是否有必要检查ToEndMember.DeleteBehavior上面的代码中是否OperationAction.None

感谢您的帮助! -Emil

0 个答案:

没有答案