簡體   English   中英

在實體上調用GetProperties時如何避免返回某些屬性和外來實體?

[英]How to avoid returning certain properties and Foreign Entities when calling GetProperties on an Entity?

我正在打電話:

var properties = person.GetType().GetProperties(BindingFlags.DeclaredOnly |
                                                        BindingFlags.Public |
                                                        BindingFlags.Instance);

這返回了我想要的東西,它還返回了一個我不想要的屬性,稱為更新,但是我可以輕松地忽略它。 它還返回我不想包括的CarReferenceCar 如何排除這些字段? 當前,我有一個排除屬性的列表,如果名稱與其中之一匹配,我將跳過它,但是我希望它更通用,而不是硬編碼"CarReference""Car"

我不知道這是否是您要尋找的內容,但這是一個可以幫助您的代碼段。 對於自動生成的實體框架“實體”類的某些屬性,有一些標准:

var flags = BindingFlags.Public | BindingFlags.Instance;
var destinationProperties = typeof(TDestination).GetProperties(flags);

foreach (var property in destinationProperties)
{
    var type = property.PropertyType;

    // Ignore reference property (e.g. TripReference)
    if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(EntityReference<>))
    {
        // ...
    }

    // Ignore navigation property (e.g. Trips)
    if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(EntityCollection<>))
    {
        // ...
    }

    // Ignore ID (edmscalar) property (e.g. TripID)
    if (property.GetCustomAttributes(typeof(EdmScalarPropertyAttribute), false).Any())
    {
        // ..
    }

使用PropertyType中列出的“名稱空間”屬性,將通過以下語句跳過外部實體:if(type.Namespace!=“ System”)

        using (var db = new Entities.YourEntities())
        {
            var originalObj = db.MyTable.FirstOrDefault();

            foreach (var prop in originalObj.GetType().GetProperties())
            {
                var type = prop.PropertyType;

                if (type.Namespace != "System")
                    continue;

                var name = prop.Name;
                var value = prop.GetValue(originalObj, null);

                //your code here
            }
        }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM