Option: Add an ignore attribute
This issue is a followup on @IgorMamushin's feature request in #3.
The original request goes:
Ignore some properties. (Usually for ignore property used attributes. It will be well if we can set our ignore attribute, for example "JsonIgnore"). I did it in my fork. It is worked. But i did it wrong, it broke design.
Thank you for providing feedback.
This is a very reasonable request, I'll be happy to accept a PR on it if you fix up your fork, or I can implement it myself when I'll have the time.
I definitely would not like adding Newtonsoft.Json as a dependency just for this attribute, (or any other library - dependencies have a high maintenance cost when authoring libraries.). So ignoring should happen using a custom attribute class. I'm not great at naming things, CloneIgnore maybe?
There is also another question. Not cloning a property can mean two very different things to me:
- Instead of deep cloning it, keep the original, so
clone.SomeIgnoredProp == original.SomeIgnoredProp - Set it to null / 0, so
clone.SomeIgnoredProp == default
Which is the preferred semantics here? Or should it be configurable? (We can make it configurable in a simple way using the attribute)
If setting will have "Type" then you don't needed add Newtonsoft.Json. And i can use it like this:
ObjectCloner.Clone(myObject, new Settings
{
IgnorAttributeType = typeof(JsonIgnoreAttribute)
});
Actually if cloner will have itself attribute, it will be OK.
Implementing settings is a tad more complicated than just using a custom attribute, but of course sooner or later it will need to be done.
What about my other question?
About second question. I think it will good if we can select this in attribute. I think it can be useful sometimes. But default value must will "clone.SomeIgnoredProp == default".
I need this, it is cloning my primary key which I do not want.
Hi, @enkodellc! You may watch my fork: https://github.com/IgorMamushin/ObjectCloner
Solution isn't good enough, but maybe you will do in your own way :) I did it for one of my previous project. So, I used JsonIgnore there.
But maybe you may use automapper, it can be more flexible. Or source generator.
@IgorMamushin I did find a way, I added a detach method for EF to reset the Key:
//used when you use ShallowClone or DeepClone and need to get rid of the index
public void Detach<T>(T entity) where T : class
{
Entry(entity).State = Microsoft.EntityFrameworkCore.EntityState.Detached;
}
@IgorMamushin you should submit your code as a PR
Ya, i don't think that it's a good solution anyway.
Maybe i will find time for do it well