bchavez / Bogus

:card_index: A simple fake data generator for C#, F#, and VB.NET. Based on and ported from the famed faker.js.
Other
8.51k stars 483 forks source link

private setters workaround is not working for generic types #551

Open SDivya03 opened 2 months ago

SDivya03 commented 2 months ago

Bogus NuGet Package

v35.01

.NET Version

4.7.1

Visual Studio Version

No response

What operating system are you using?

Windows

What locale are you using with Bogus?

en_GB

What's the problem?

Class T { public List Hobbies; public List ITems;

}

How to send generic class and Generic property type and create a expression to make the below code work.

Faker faker = new Faker(); var model = new User(); var result = faker.CreateRuleForSetters(model);

// Generate fake data for the Person model var fakePerson = result.Generate(1);

-----------Added Extension method to create rule for setters public static Faker RuleForList<T, U>(this Faker fakerT, Expression<Func<T, List>> propertyOfListU, Func<Faker, List> itemsGetter) where T : class { var func = propertyOfListU.Compile();

    fakerT.RuleFor(propertyOfListU, (f, t) =>
    {
        var list = func(t);
        var items = itemsGetter(f);

        list.AddRange(items);

        return items;
    });

    return fakerT;
}

---- public static Faker CreateRuleForSetters(this Faker fakerT, T model) where T : class { // Get properties without setters var propertiesWithoutSetters = typeof(T) .GetProperties() .Where(prop => !prop.CanWrite);

    // Add rules for properties without setters
    foreach (var property in propertiesWithoutSetters)
     {
        //Create lambdaexpression with type Expression<Func<T, List<U>> for this proertry 
        // like u =.u. Hobbies 

        fakerT.RuleForList(lambdaExpression, func);

    }
    return fakerT;
}

It works if we specify the generic types manually , not other way round.

Provide LINQPad Example

---- public static Faker CreateRuleForSetters(this Faker fakerT, T model) where T : class { // Get properties without setters var propertiesWithoutSetters = typeof(T) .GetProperties() .Where(prop => !prop.CanWrite);

    // Add rules for properties without setters
    foreach (var property in propertiesWithoutSetters)
     {
        //Create lambdaexpression with type Expression<Func<T, List<U>> for this proertry 
        // like u =.u. Hobbies 

        fakerT.RuleForList(lambdaExpression, func);

    }
    return fakerT;
}

What other possible solutions or alternatives have you considered?

Generating an lambda expression works fine, but genering with specific types like Expression<Fun<T,List> does not work.