Automatic extension method generation for easy updating of existing class instances
See original GitHub issueProposal
I’m loving the library, but I think it would be very helpful to have the source generator automatically create extension methods for the updating of existing class instances. This would allow classes to become more “record-like”, allowing updates in-place.
I’m proposing here that the “lifting” method to be called BuildNew()
, but I dont think this is ideal, and I think a better name should be thought of. I would call it With()
, but that conflicts with the current WithX
naming convention of the existing builders.
Example API:
[AutoGenerateBuilder(generateSetters: true)]
public class User
{
public string Name { get; set; }
public string Gender { get; set; }
}
...
var user = await dbContext.Users.FirstAsync();
user.BuildNew() // `BuildNew` originates from an auto-generated extension method class in UserBuilder.g.cs. Lifts user into a UserBuilder
.WithName("New Name") // usual updates happen here
.Build(); // Updates the object in-place.
// OPTIONALLY if generateSetter == True
user.SetName("Newer Name"); // Sets the name
await dbContext.SaveChangesAsync(); // user's Name property is updated.
// also allow for operations on items in a collection
var users = dbContext.Users.Where(x => x.Gender == "Male").ToListAsync();
users.SetGender("Female") // Updates all elements in-place. Could also use `BuildNew()` syntax.
dbContext.SaveChangesAsync();
I feel like this is a natural continuation of the current library. It appears like you’re supposed to be able to use UsingInstance
for this purpose to update existing instances in-place, but I can’t get it to work. This would also bring existing non-record classes to be more “record like”.
Issue Analytics
- State:
- Created 6 months ago
- Comments:6 (6 by maintainers)
Top GitHub Comments
Official NuGet will be released shorty.
@StefH I’ve given it a test, looks great! Appreciate it.