I have an Angular client and create a POST request with this body:
{"Name":"example","Currency":"EUR"}
I Use Odata protocol and my Controller is:
[HttpPost, ODataRoute("Templates")]
public IActionResult Insert([FromBody] Template value)
{
if (!ModelState.IsValid)
return BadRequest(ModelState);
value.Id = Guid.NewGuid();
_context.Templates.Add(value);
_context.SaveChanges();
return Created(value);
}
with Template:
public class Template
{
public Guid Id { get; set; }
public string Name { get; set; }
public Currency Currency { get; set; }
}
and Currency:
[Serializable]
public class Currency : StringEnumeration<Currency>
{
public static Currency EUR = new Currency("EUR", "EUR");
public static Currency USD = new Currency("USD", "USD");
Currency() { }
Currency(string code, string description) : base(code, description) { }
}
Currency is a particular class because it has private constructors and for this reason i can't create a new instance of Currency. I want use ones of the existing instances (EUR or USD).
(StringEnumeration support a Parse and TryParse Method and return the correct instance)
Standard Configuration:
public void ConfigureServices(IServiceCollection services)
{
services.ConfigureCors();
services.AddOData();
services.ConfigureIISIntegration();
services.AddMvc()
.SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.AddDbContext<GpContext>(option => option
.UseSqlServer(Configuration.GetConnectionString(GpConnection)));
}
My problem is when the client call POST on http://localhost:4200/template with the body: {"Name":"example","Currency":"EUR"}
The Model Bindel cannot Convert "EUR" in Currency.EUR instance, so i want provide something to help model binder to create Template with Currency property with the instance Currency.EUR
This is the error generated: A 'PrimitiveValue' node with non-null value was found when trying to read the value of the property 'Currency'; however, a 'StartArray' node, a 'StartObject' node, or a 'PrimitiveValue' node with null value was expected.
In my project i have many classes with Currency property inside.
I tryed to use IModelBinder on Template class and it works, but i dont want write a modelBinder for any Currency Property.
I tried with JsonConverter, but it doesn't work for me (maybe something wrong)
My Expected result is a Template instance with this values:
Id = defaluf(Guid)
Name = "example"
Currency = Currency.EUR