Wie bin ich polymorphe Eigenschaften in .NET -Kernmodellen?C#

Ein Treffpunkt für C#-Programmierer
Guest
 Wie bin ich polymorphe Eigenschaften in .NET -Kernmodellen?

Post by Guest »

Ich verwende JSONDEVIVIVETTYPE für polymorphe Modelle im .NET -Kern und möchte eine korrekte Bindung im Controller sicherstellen. Senden Sie eine JSON -Nutzlast an diesen Endpunkt. Der korrekte abgeleitete Typ für die Warnung wird instanziiert und gebunden. Ist dieser Ansatz korrekt oder gibt es eine bessere Möglichkeit, die polymorphe Bindung in .NET Core zu bewältigen?

Code: Select all

[JsonPolymorphic(TypeDiscriminatorPropertyName = "AlertType")]
[JsonDerivedType(typeof(ManufacturingAlert), typeDiscriminator: "manufacturingAlert")]
[JsonDerivedType(typeof(DeviationAlert), typeDiscriminator: "deviationAlert")]
[JsonDerivedType(typeof(TempdevAlert), typeDiscriminator: "temporaryDeviationAlert")]
public abstract class Alert
{
public int AlertId { get; set; }
public DateTime CreatedDate { get; set; } = DateTime.Now;
public AlertType AlertType { get; set; }
}

public enum AlertType
{
manufacturingAlert,
deviationAlert,
tempDevAlert
}
< /code>
public class AlertCreateRequest
{
public DateTimeOffset DateTime { get; set; }
public AlertType alertType { get; set; }
public Alert alert { get; set; }
}
< /code>
public class ManufacturingAlert : Alert
{
public string HowP { get; set; }
}
< /code>
builder.Services.AddControllers()
.AddJsonOptions(options =>
{
options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
options.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
options.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.Preserve;
});

JsonSerializerOptions options = new JsonSerializerOptions()
{
WriteIndented = false,
ReferenceHandler = ReferenceHandler.IgnoreCycles,
PropertyNameCaseInsensitive = true,
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
};
< /code>
[HttpPost]
public async Task CreateAsync([FromBody] AlertCreateRequest request)
{
// PatientRecord structure is same as PatientRecordCreateRequest
var patient = await _alertService.CreateAlertAsync(request.alert);
return Ok(patient);
}

Quick Reply

Change Text Case: 
   
  • Similar Topics
    Replies
    Views
    Last post