繁体   English   中英

EF代码优先-检测给定类型的一对多关系属性

[英]EF Code first - Detect one-to-many relationships property for given type

我们知道,我们不需要使用数据注释为一对多关系进行配置,而是按照约定配置的一对多关系。

在下面的示例中, ICollection<Student> Students是一个关系属性

public class Student
{
    public Student() { }

    public int StudentId { get; set; }
    public string StudentName { get; set; }

    public virtual Standard Standard { get; set; }
}

public class Standard
{
    public Standard()
    {
        Students = new List<Student>();
    }
    public int StandardId { get; set; }
    public string Description { get; set; }

    public virtual ICollection<Student> Students { get; set; }
}

所以我的问题是,如何检测给定类型的关系属性? 我的目标是测试属性的值及其包含的项目数量

像这样:

static void Test(object givenInstanse)
{
    foreach (PropertyInfo p in TryGetOneToManyRelationshipsPropertys(typeof(givenInstanse), dc))
    {
        var val = (ICollection)p.GetValue(givenInstanse);
        Console.WriteLine(val.Count);
    }
}

static IEnumerable<PropertyInfo> TryGetOneToManyRelationshipsPropertys(Type t, DbContext dc)
{
    // ...
}

以最简单的形式(不考虑任何自定义属性或自定义映射)。 你可以这样做:

IEnumerable<PropertyInfo> GetOneToManyRelationships<T>()
{
    var collectionProps = from p in typeof(T).GetProperties()
                          where p.PropertyType.IsGenericType
                                && p.PropertyType.GetGenericTypeDefinition() 
                                                   == typeof(ICollection<>)
                          select p;

    foreach (var prop in collectionProps)
    {
        var type = prop.PropertyType.GetGenericArguments().First(); 

        // This checks if the other type has a One Property of this Type.
        bool HasOneProperty = type.GetProperties().Any(x => x.PropertyType == typeof(T));

        if(!HasOneProperty)
        {
            string pkName = typeof(T).Name + "Id";

            HasOneProperty = type.GetProperties().Any(x => x.Name.Equals(pkName, 
                                                      StringComparison.OrdinalIgnoreCase));
        }

        if (HasOneProperty)
        {
            yield return prop;
        }
    }
}

用法:

var oneToManyProps = GetOneToManyRelationships<Standard>();

foreach(var prop in oneToManyProps)
{
    Console.WriteLine(prop.Name);
}

输出:

Students

您可以扩展它以检查在属性上标记的属性,但是我将其留给您,因为它不在您的问题范围内。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM