如何将我从数据库中获得的实体绑定到我的请求的 DTO?



我有一个DTO(数据传输对象(类。也许这个类的名称不正确,但我通常将其称为请求模型或DTO,并将JSON请求中的数据映射到此类。我给你举个例子:

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; }
}

正如你所看到的,我这里有两处房产。一个是简单的Title,只是一个字符串,但第二个是我的数据库实体。对于这个项目,我使用实体框架核心和.NET核心MVC 2.2。我将向您展示我的数据库上下文:

public class ApplicationDbContext : IdentityDbContext
{
private readonly string _connectionString;
public DbSet<Category> Category { get; set; }
public DbSet<Application> Applications {get; set;}
... more props here ...

类别模型的代码:

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;
}
}

在控制器中,我有以下方法:

public IActionResult Save([FromBody] SaveRequest request) {...}

正如你所看到的,在这里我试图捕捉SaveRequest模型。

现在你知道我的代码了。这是关于我的问题。我发送以下JSON:

{
"title": "Hello!! How are you!!!",
"category_id": 777
}

我想将category_id请求参数绑定到真正的CategoryEF实体。我的意思是,让EF Framework找到具有给定id的Category,然后将其绑定到DTO类中的Category属性。如果具有给定id的Category实体不存在,则将新的模型错误添加到模型状态(为客户端显示(。如果它存在,我希望将它绑定到我的DTO。我已经阅读了这份文档,也看到了一些关于[BindProperty]的内容,但我不明白它是否适合我的问题。

实体框架不能自动做到这一点,我认为你可以构建一个自定义的模型绑定

然而,你可以在你的控制器中做到这一点

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; }
} 

在您的控制器中

public IActionResult Save([FromBody] SaveRequest request) {
var category = context.categories.where(c => c.id == request.Category_id).FirstOrDefaults();
if(category == null) 
return NotFound();
...
}

最新更新