Reputation: 3058
I have a DTO (data transfer object) Class. Maybe it's incorrect name for this class but I usually call it as Request model or DTO and I map data from my JSON request to this class. I'll give you an example:
public class SaveRequest
{
[JsonProperty("category_id")]
[Required(ErrorMessage = "You have to choice category!!!")]
public Category Category { get; set; }
[JsonProperty("title")]
[Required(ErrorMessage = "You have to type title!!!")]
public string Title { get; set; }
}
As you can see I have two properties here. One - is simple Title
- just a string, but the second - is my database entity. For this project I use Entity framework Core and .NET Core MVC 2.2. I'll show you my database context:
public class ApplicationDbContext : IdentityDbContext
{
private readonly string _connectionString;
public DbSet<Category> Category { get; set; }
public DbSet<Application> Applications {get; set;}
... more props here ...
And Category model's code:
public class Category
{
public int CategoryId { get; set; }
public string Name { get; set; }
public DateTime CreatedAt { get; set; }
public List<Application> Applications { get; set; }
public Category()
{
CreatedAt = DateTime.UtcNow;
}
}
In the controller I have the following method:
public IActionResult Save([FromBody] SaveRequest request) {...}
As you can see, here I'm trying to catch SaveRequest
model.
So, now you know all about my code. This is about my issue. I send the following JSON:
{
"title": "Hello!! How are you!!!",
"category_id": 777
}
I would like to bind category_id
request param to real Category
EF entity. I mean, ask EF Framework to find me Category
with given id, and then bind it to Category
property in the DTO class. If Category
entity with given id does not exist than add new model error to model state (to showing it for a client). If it exists, I would like to have it bound to my DTO. I have read this documentation and I have seen something about [BindProperty]
, but I dont understand is it suitable for my issue or not.
Upvotes: 0
Views: 687
Reputation: 249
entity framework can't do that automatically , i think you can build a custom model binder
however, you can do that in your controller
in DTO
public class SaveRequest
{
[JsonProperty("category_id")]
[Required(ErrorMessage = "You have to choise category!!!")]
public int Category_ID { get; set; }
[JsonProperty("title")]
[Required(ErrorMessage = "You have to type title!!!")]
public string Title { get; set; }
}
in your controller
public IActionResult Save([FromBody] SaveRequest request) {
var category = context.categories.where(c => c.id == request.Category_id).FirstOrDefaults();
if(category == null)
return NotFound();
...
}
Upvotes: 1