Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Feature Request] ObjectReader.Create() option to filter out properties with certain Attribute #78

Open
ThaDaVos opened this issue Aug 27, 2019 · 1 comment

Comments

@ThaDaVos
Copy link

ThaDaVos commented Aug 27, 2019

It would be great if somehow properties could be ignored which have a certain Attribute currently doing it as follows to filter out all properties with the NotMappedAttribute but seems a bit slow:

var accessor = TypeAccessor.Create(typeof(T));
var fields = accessor.GetMembers().Where(x => !x.IsDefined(typeof(NotMappedAttribute))).Select(x => x.Name).ToArray();
using var reader = ObjectReader.Create(data, fields);
@cajuncoding
Copy link

cajuncoding commented Jan 25, 2022

Seems like some caching on the fields would solve the slow issue?

Here's a Helper class that wraps it up with a cache.... can't use a Custom Extension because TypeAccessor is abstract, doesn't use Generics, and doesn't provide public access to the internal Type being handled by FastMember.... but the helper is just as easy to consume...

public static class TypeAccessorHelpers
{
    private static readonly ConcurrentDictionary<Type, Lazy<string[]>> _accessorFieldsLazyCache = new();

    public static string[] GetOnlyMappedFieldsForType<T>()
    {
        var objectType = typeof(T);
        return _accessorFieldsLazyCache.GetOrAdd(objectType, new Lazy<string[]>(() =>
        {
            var accessor = TypeAccessor.Create(objectType);
            return accessor.GetMembers()
                .Where(x => !x.IsDefined(typeof(NotMappedAttribute)))
                .Select(x => x.Name)
                .ToArray();
        }))?.Value;
    }
}

Usage:

var fields = TypeAccessorHelpers.GetOnlyMappedFieldsForType<T>();
using var reader = ObjectReader.Create(data, fields);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants