V
V
VanilaSpirit2020-07-09 20:37:28
ASP.NET
VanilaSpirit, 2020-07-09 20:37:28

ASP.NET Do all models need a base model?

In one of the projects I found the following construction:
There is a base model containing only the key (Id). All other models inherit from it.

public class BaseModel
    {
        [Key]
        public Guid Id { get; set; }
    }


Example with BaseModel:
public class Player : BaseModel
    {
        [Required]
        [Display(Name = "Имя")]
        public string Name { get; set; }

        [Required]
        [Display(Name = "Фамилия")]
        public string Surname { get; set; }
    }


Is this some kind of necessary specificity, or can it be completely dispensed with in real projects?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
P
Planet_93, 2020-07-09
@VanilaSpirit

This is quite normal practice. The main thing is to determine whether there will be models with a set of common fields in the system.
For example, there are databases where data is not deleted, and records are set to Deleted. Adding and editing each entry is fixed. In such cases, it makes sense to move the common fields to the base class and already inherit it.

/// <summary>
  /// Базовый класс для всех классов модели приложения
  /// </summary>
  public abstract class BaseEntity
    {
        /// <inheritdoc />
        /// <summary>
        /// Идентификатор
        /// </summary>
        [Key]
        public virtual long Id { get; set; }
        /// <inheritdoc />
        /// <summary>
        /// Дата занесения записи
        /// </summary>
        public DateTime CreatedOn { get; set; } = DateTime.Now;
        /// <summary>
        /// Дата модификации записи
        /// </summary>
        public DateTime UpdatedOn { get; set; } = DateTime.Now;
        /// <inheritdoc />
        /// <summary>
        /// Активен
        /// </summary>
        [DefaultValue(true)]
        public bool Active { get; set; } = true;
        /// <inheritdoc />
        /// <summary>
        /// Удален
        /// </summary>
        [DefaultValue(false)]
        public bool Deleted { get; set; }
    }

V
Vladimir Korotenko, 2020-07-09
@firedragon

As for me, this project was made for mongo db, in other cases it is much more convenient to store less voluminous keys. For example, I have byte, short, int, long, guid

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question