简体   繁体   English

使用反射访问拥有的属性

[英]Accessing Owned properties with reflection

I'm struggling to dynamically expose a list of values containing Name, Database Column Name and value of an entity containing owned types.我正在努力动态公开包含名称、数据库列名称和包含拥有类型的实体的值的值列表。

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

Owning relationship declared in model builder model builder声明的所有权关系

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

With other declarations like column name.与列名等其他声明。 This information is stored in a single table, this reduced example with an int Id and a string Number.此信息存储在单个表中,此简化示例包含一个 int Id 和一个字符串 Number。

Using Reflexion, I can get the values of Foo properties.使用 Reflexion,我可以获得 Foo 属性的值。 Then I identify owned types and then call my function again to have the bindings off owned types properties, but it fails.然后我确定了拥有的类型,然后再次调用我的 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)
        }
    }
}

Thank you谢谢

OK, I found my way.好的,我找到了我的路。 I have to get the owned object itself before relying on propertyInfo[]:在依赖 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