-
-
Notifications
You must be signed in to change notification settings - Fork 514
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
Passing Parameters for Rules #460
Comments
Hi @shawnwildermuth, Thank you for posting. Every Here is one approach (of probably many) shown below: void Main()
{
var orderFaker = new Faker<Order>()
.RuleFor(o => o.OrderId, f => f.IndexFaker)
.RuleFor(o => o.CustomerId, (f,o) => f.FromContext(nameof(o.CustomerId)));
var custFaker = new Faker<Customer>()
.RuleFor(c => c.Id, f => f.IndexFaker)
.RuleFor(c => c.Name, f => f.Name.FullName())
.RuleFor(c => c.Orders, f => orderFaker.WithContext(nameof(Order.CustomerId), f.IndexFaker).Generate(3));
custFaker.Generate(3).Dump();
}
public static class ExtensionsForIssue460
{
public static object FromContext(this Faker faker, string key)
{
var fakerContext = faker as IHasContext;
return fakerContext.Context[key];
}
public static Faker<T> WithContext<T>(this Faker<T> fakerT, string propertyName, object value) where T : class
{
var internals = fakerT as IFakerTInternal;
var faker = internals.FakerHub;
var fakerContext = faker as IHasContext;
fakerContext.Context[propertyName] = value;
return fakerT;
}
}
public class Order
{
public int OrderId { get; set; }
public int CustomerId { get; set; }
}
public class Customer
{
public int Id { get; set; }
public string Name { get; set; }
public List<Order> Orders { get; set; }
} I'm not super convinced yet that introducing an overloaded Feel free to continue the conversation or close the issue if you find the solution above satisfactory. Thanks, |
That's awesome! Thanks, this using Context makes more sense than the overload. Just glad there is a way to do this. |
Please describe why you are requesting a feature
I'd like to be able to pass a parameter to the GenerateXXX() methods so that I can a Rule can use that parameter for initialization
Please provide a code example of what you are trying to achieve
Please answer any or all of the questions below
AFAIK
Post processing the generated data
No.
If the feature request is approved, would you be willing to submit a PR?
Yes
The text was updated successfully, but these errors were encountered: