A
A
AlkesPro2020-05-11 15:34:43
ASP.NET
AlkesPro, 2020-05-11 15:34:43

How to create a limit on the number of elements for a one-to-many relationship (ASP.NET core MVC + EF)?

I have a conditional user. A model with relations one user - many models is attached to it.

I need that for one user, when creating a new model or editing to create a new relationship in SQL, there is a limit on the number of models to 4. That's 1 user and a maximum of 4 models.
User definition:

public class User
    {
        [MaxLength(30)] [NotNull]
        public string m_Name { get; set; }
        [Key]
        public int m_ID { get; set; }

        public List<Book> Book { get; set; }
    }


Defining a model for communication:
public class Book
    {
        [Key]

        public int m_ID { get; set; }
        [MaxLength(40)] [NotNull]
        public string m_Name { get; set; }
        [MaxLength(100)] [NotNull]
        public string m_Description { get; set; }

        public int? UserID { get; set; }
        public User User { get; set; }
    }


And for example, I will attach the controller code that creates the book:
public IActionResult CreateBook()
        {
            return View();
        }

        [HttpPost]
        public async Task<IActionResult> CreateBook(Book book)
        {
            db.Books.Add(book);
            await db.SaveChangesAsync();
            return RedirectToAction("Index");
        }


<form asp-action="CreateBook" asp-controller="Home">
        <div class="form-group">
            <label asp-for="m_Name" class="control-label">Название книги</label>
            <input type="text" maxlength="40" placeholder="Введите название книги, максимальная длинна - 40 символов" asp-for="m_Name" class="form-control" />
        </div>

        <div class="form-group">
            <label asp-for="m_Description" class="control-label">Описание книги</label>
            <input type="text" maxlength="100" placeholder="Введите краткое описание книги, максимальная длинна - 100 символов" asp-for="m_Description" class="form-control" />
        </div>

        <div class="form-group">
            <label asp-for="UserID" class="control-label">ID пользователя</label>
            <input type="text" maxlength="4" placeholder="Введите id нового пользователя" asp-for="UserID" class="form-control" />
        </div>

        <div class="form-group">
            <input type="submit" value="Отправить" class="btn btn-outline-dark" />
        </div>
    </form>

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question