private setters workaround is not working for generic types
- Dominant language
- C#
- Stars
- 9.7k
- Forks
- 538
- PR merge metrics
- No merged PRs in 30d
Description
### 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(this Faker fakerT, Expression>> propertyOfListU, Func> 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> 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> 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> does not work.
Contributor guide
Research direction
Start with the CreateRuleForSetters and RuleForList extension methods shown in the issue, then reproduce the generic List and List cases in a small Bogus example. Compare them with the manually specified generic-type case; done means the generic property expressions work without manually supplying the types.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- csharp
- Domain
- tooling
- Issue type
- Bug
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Needs clarification
- Newbie friendliness
- 25/100