简体   繁体   English

ASP.NET Core API 模型概念

[英]ASP.NET Core API model concept

I'm working on a sample app that exposes a restful API.我正在开发一个示例应用程序,它公开了一个宁静的 API。 I'm also using EF core to map entities mkd to a SQLite db.我还使用 EF 核心将实体 mkd 映射到 SQLite 数据库。

Each entity has an ID property that is auto-generated and is unique.每个实体都有一个自动生成且唯一的 ID 属性。

The api expose a method for the creation of an entity by providing a model object. api 通过提供模型对象公开了创建实体的方法。 At the moment I'm using the same model that is mapped to EF Core (with the ID field included).目前我正在使用映射到 EF Core 的相同模型(包括 ID 字段)。

I honestly don't think that exposing the ID field during the creation of an entity is a good practice, so I thought to create another model without the ID field that will be passed to the create method and then map it the model that EF is using.老实说,我不认为在创建实体期间公开 ID 字段是一个好习惯,所以我想创建另一个没有 ID 字段的模型,该模型将传递给 create 方法,然后将其映射到 EF 所在的模型使用。

Is it a good practice or is it too overkill?这是一个好习惯还是太过分了?

Am I missing something?我错过了什么吗?

What you are essentially doing is the use of a DTO/ViewModel instead of the model object directly, and that is considered a good practice.您本质上所做的是直接使用 DTO/ViewModel 而不是模型对象,这被认为是一种很好的做法。 It saves you from the problem of over-posting as well.它也可以避免过度发布的问题。 Alternatively, you can choose to Bind specific properties as well - refer to https://www.hanselman.com/blog/ASPNETOverpostingMassAssignmentModelBindingSecurity.aspx或者,您也可以选择绑定特定属性 - 请参阅https://www.hanselman.com/blog/ASPNETOverpostingMassAssignmentModelBindingSecurity.aspx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM