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

时间:2019-11-17 16:50:00

标签: c# .net-core entity-framework-core

我有一个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-只是一个字符串,但是第二个-是我的数据库实体。对于此项目,我使用实体框架Core和.NET Core 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请求参数绑定到真实的Category EF实体。我的意思是,请EF框架找到具有给定ID的Category我,然后将其绑定到DTO类中的Category属性。如果不存在具有给定ID的Category实体,则向模型状态添加新的模型错误(以向客户端显示)。如果存在,我希望将其绑定到我的DTO。我已经阅读过documentation,并且已经了解了有关[BindProperty]的一些内容,但我不知道它是否适合我的问题。

1 个答案:

答案 0 :(得分:1)

实体框架无法自动执行此操作,我认为您可以构建自定义模型活页夹

但是,您可以在控制器中做到这一点

在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();
 ...
}