Home > Enterprise >  Removing setter from Model Id
Removing setter from Model Id

Time:12-19

Following this tutorial from Microsoft gives me this Model for a TodoItem:

namespace TodoApi.Models
{
    public class TodoItem
    {
        public long Id { get; set; }
        public string? Content { get; set; }
        public bool Completed { get; set; }
    }
}

I do not want the user to be able to update or set the Id property. My colleauge solved this by creating a separate model for posting and putting TodoItems - following some tutorial online I think. My idea was to just remove the setter from the property, and after testing the only error I got was that I had to set a PrimaryKey for the Model. I ended up with this:

using Microsoft.EntityFrameworkCore;

namespace TodoApi.Models
{
    [PrimaryKey(nameof(TodoItem.Id))]
    public class TodoItem
    {
        public long Id { get; }
        public string? Content { get; set; }
        public bool Completed { get; set; }
    }
}

The code worked, but since I am new and learning I want to know if this is a no-no or if this is okay to do. I cannot find anyone else doing the same online so I thought I'd ask here. Thanks in advance :)

Edit: I now see that the put method returns a 400 Bad Request, so I gues that means it's a no-no? What would be the best way to solve this issue, is it to create a separate model? Or maybe define a setter which doesn't do anything?

CodePudding user response:

You could make a constructor to set initial values and make the setter for Id private.

public class TodoItem
{
    public long Id { get; private set; }
    public string? Content { get; set; }
    public bool Completed { get; set; }

    public TodoItem(long id, string? content, bool completed)
    {
        Id = id;
        Content = content;
        Completed = completed;
    }
}

Edit

You could make the setter not actually set:

public class TodoItem
{
    private long _id;
    public long Id
    {
        get => _id;
        set {}
    }
    public string? Content { get; set; }
    public bool Completed { get; set; }
}

In this case you would probably not get an error because there is a setter but it would also not change the Id.

CodePudding user response:

in practice, we use a readmodel that has private set for its properties to avoid unwanted state changes and a write model with an accessible set that updates or creates the persisted data, you can also pass by a viewModel that exposes only the state of your entity and a DTO to CRUD your data

  • Related