简体   繁体   English

使用 Entity Framework Core 在 ASP.NET Core WebAPI 中使用“DatabaseGenerated”处理属性

[英]Handling properties with "DatabaseGenerated" in ASP.NET Core WebAPI with Entity Framework Core

I have the following model class:我有以下 model class:

public class Item
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    [Required(ErrorMessage = "You must provide a name.")]
    [MaxLength(255)]
    public string Name { get; set; }
}

When doing GET operations I want to return the object with the Id property, so the user can know what ID to query for update or specific GET.在执行 GET 操作时,我想返回带有Id属性的 object,这样用户就可以知道查询更新或特定 GET 的 ID。 However I DON'T want the client to be able to provide a value for the ID property when doing POST requests and want it to be generated by the database as part of the IDENTITY thing.但是,我不希望客户端在执行 POST 请求时能够为 ID 属性提供值,并希望它由数据库生成作为IDENTITY事物的一部分。

How would I achieve that?我将如何实现这一目标?

You cannot manually set the value of an Identity (Auto Increment) column.您不能手动设置标识(自动递增)列的值。

Here, in the below example PurchaseId is an Identity column.在这里,在下面的示例中,PurchaseId 是一个标识列。

purchase.PurchaseId = 6;
_dbContext.Purchases.Add(purchase);
_dbContext.SaveChanges();

When saving changes to the database the EF Core throws Microsoft.EntityFrameworkCore.DbUpdateException with Cannot insert explicit value for identity column in table 'Purchases' when IDENTITY_INSERT is set to OFF.将更改保存到数据库时,EF Core 抛出Microsoft.EntityFrameworkCore.DbUpdateExceptionCannot insert explicit value for identity column in table 'Purchases' when IDENTITY_INSERT is set to OFF. error.错误。

So, by default, you cannot assign the value.因此,默认情况下,您无法分配该值。

But this is not the issue here.但这不是这里的问题。

The bigger issue is that you are exposing the Domain classes to your client.更大的问题是您将域类公开给您的客户。 This flaw in API design can lead to more than this problem. API 设计中的这个缺陷可能导致的问题不止于此。

You have to create a DTO eg CreateItemDTO whose only responsibility is to contain all the methods required to create an Item in the database.您必须创建一个 DTO,例如 CreateItemDTO,它的唯一职责是包含在数据库中创建项目所需的所有方法。

The same way you should not expose Item class in the GET request.同样,您不应在 GET 请求中公开项目 class。 This leads to a problem when API related columns that are not for clients gets exposed.当 API 不针对客户端的相关列被暴露时,这会导致问题。 Create a GetItemDTO which would only contain information that is important for the GET request.创建一个 GetItemDTO,它只包含对 GET 请求很重要的信息。

CreateItemDTO创建项目DTO

public class CreateItemDTO
{
    [Required(ErrorMessage = "You must provide a name.")]
    [MaxLength(255)]
    public string Name { get; set; }
}

Read Exposing domain models over API for more information.阅读API 上的公开域模型以获取更多信息。

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

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