I'm building a Web API using ASP.NET and EntityFramework Core with DB Migrations. In my Rental.cs class I have an attribute Price which is not nullable in the database (thus using [Required]). In my HTTP Post request from client to server I want to send a Rental-object but without the Price-attribute (since this should be figured out on the server). This doesn't work since Price is [Required].
I want Price to be required in the database/model but not in the request from frontend to backend. How could I solve this problem? Should I split it into two classes (one for DB and one for post request)?
Rental.cs
public class Rental
{
public int RentalId { get; set; }
[Required]
public double Price { get; set; }
[Required]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public DateTime OrderTime { get; set; }
[Required]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public DateTime Expires { get; set; }
...
RentalController.cs
[HttpPost]
public async Task<ActionResult<Rental>> PostNewRental([FromBody] Rental rental)
{
// Want to change the Price attribute here by fetching from somewhere else.
var res = await _rentalService.AddNewRental(rental);
return Ok(res);
}
CodePudding user response:
Ideally, you should have separate types for DTOs (that type that use in controller action) and models or entities in your case (the type that you use for EF).
For example, you DTO should be
public class RentalDto
{
public int RentalId { get; set; }
public DateTime OrderTime { get; set; }
public DateTime Expires { get; set; }
}
Your entity model should be
public class Rental
{
public int RentalId { get; set; }
[Required]
public double Price { get; set; }
[Required]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public DateTime OrderTime { get; set; }
[Required]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public DateTime Expires { get; set; }
}
You can then use a library like AutoMapper to copy dto values into entity.
For more details, read about DTOs vs Models