繁体   English   中英

使用反射访问拥有的属性

[英]Accessing Owned properties with reflection

我正在努力动态公开包含名称、数据库列名称和包含拥有类型的实体的值的值列表。

public class Foo {
    public int Id { get; set; }
    public Certificate Certificate { get; set; }
}

[Owned]
public class Certificate {
    public string Number { get; set; }
    // Some logic here
}

public class PropBinding()
{
    public string Name{ get; set; }
    public string ColName{ get; set; }
    public string Content{ get; set; }
}

model builder声明的所有权关系

modelBuilder.Entity<Foo>(entity =>
    entity.OwnsOne(e => e.Certificate)
          .UsePropertyAccessMode(PropertyAccessMode.Property)

与列名等其他声明。 此信息存储在单个表中,此简化示例包含一个 int Id 和一个字符串 Number。

使用 Reflexion,我可以获得 Foo 属性的值。 然后我确定了拥有的类型,然后再次调用我的 function 以绑定拥有的类型属性,但它失败了。

foreach(var propBinding in GetBindings(myFoo, myFoo.GetType())
{
    // no problem 
}

var owned = contentType.GetNavigations().FirstOrDefault(x => x.ForeignKey.IsOwnership);
foreach(var propBinding in GetBindings(myFoo, owned.ClrType())
{
    // success for name and colname
    // fails to get the value due to wrong type exception
}

public class IEnumerable<PropBinding> GetBindings(T entity, System.Type typeO) // Simplified for the sake of clarity
{
    var contentType = _db.Model.FindEntityType(entity.GetType());
    var storeObjectIdentifier = StoreObjectIdentifier.Table(contentType.GetTableName(), contentType.GetSchema());
    var props = typeO.GetProperties().Where(x => x.PropertyType.BaseType != null).ToList();
    foreach(var prop in props)
    {
        yield return new PropBinding() {
            Name = prop.Name,
            ColName = contentType.FindProperty(p.Name)?.GetColumnName(storeObjectIdentifier),
            Content = prop.GetValue(entity, null)
        }
    }
}

谢谢

好的,我找到了我的路。 在依赖 propertyInfo[] 之前,我必须自己获得拥有的 object:

foreach (var owned in contentType.GetNavigations().Where(x => x.ForeignKey.IsOwnership))
{
    form.AddRange(GetBindings(owned.PropertyInfo?.GetValue(content, null)));
}

暂无
暂无

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

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