简体   繁体   中英

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

I have the following 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. 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.

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.

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. 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.

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.

The same way you should not expose Item class in the GET request. This leads to a problem when API related columns that are not for clients gets exposed. Create a GetItemDTO which would only contain information that is important for the GET request.

CreateItemDTO

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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