簡體   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