Seguimos con ASP.NET+MVC


<< Errores creando WebApp MVC / Errors creating WebApp MVC

En este seguimiento a mi dominio de .NET Core y MVC desde ceros, como ya comentaba, estoy familiarizado con la parte de controladores y modelos, hago programación web, pero lo que me ha faltado es la parte de las vistas, en cuanto a como se trabajan desde VStudio con sus plantillas.

En la migración que he hecho veo que es bastante práctico ese manejo, con la obviedad de programación, de que se requiere aprender las instrucciones y atributos correspondientes.

La inserción de instrucciones de C# para procesar la información es bastante cómoda, pero hay que tener cuidado de no incluir código que debería hacer el controlador. Prácticamente hay que reducir las instrucciones al manejo de los datos para ser mostrados en la vista.

Ahora estoy modificando mi modelo y me encuentro con diferentes situaciones:

  • Agregado de nuevos campos obligatorios con una BD ya inicializada, para esto hay algunas opciones:
    1. Vaciar la tabla para volver a poblarla con registros que incluyan la nueva información para los campos obligatorios
    2. Definir un valor por defecto para los nuevos campos
    3. Modificar la población de la tabla para agregar nuevo contenido a los campos obligatorios
    4. Quitar la restricción a los nuevos campos obligatorios, realizar alguna de las opciones 2 o 3, y agregar la restricción

    Personalmente prefiero por el momento la opción 1, pero en un ambiente de pruebas e incluso de producción, sería más recomendable la opción 2

  • Agregado de Entidades relacionadas

    Experimenté algunos problemas de que no me permitía realizar los cambios por cuestión de permisos, entonces ejecuté con privilegio de Administrador para la consola de comandos y ya no tuve problemas. Pero al cambiar de base de datos en mi cadena de conexión para que generara una base limpia, me encontré con problemas de llaves foraneas

    Agregando el siguiente código a las tablas que pueden marcar problemas por rutas y referencias circulares para actualizar/eliminar datos en el archivo .cs de las migraciones, se resuelve el problema

    //...
        constraints: table =>
         {
          //...
           table.ForeignKey(
            // ...
             onDelete:ReferentialAction.NoAction,
             onUpdate:ReferentialAction.NoAction);
       
    1. Agregado de Entidades relacionadas que tienen más de un campo que apuntan a la misma tabla
  • Agregado de controladores y vistas

Como estoy utilizando consultas planas de SQL para recuperar algunos datos, estas consultas me requieren que liste todos los campos de mi entidad, así que, como no requiero la información contenida en esos campos y no fue mi intensión crear vistas, lo que hice fue poner un valor vacío o cero para cada campo que debo mencionar



In this follow up to my domain of .NET Core ans MVC since zeros, as I commented, I'm familiarized with parts about the controller and the model, I make web programming, but what I don't know is the part of the views related how to work from Visual Studio with its templates.

In the migration tha I have made I see tha it is very practical this handling, with the programming obviousness, that is required learn the corresponding commands, sentences and attributes.

The insertion of C# instructions to process the information is very comfortable, but be careful of not including code that must to do the controller. It is practically necesary reduce the instructions to the handle of data that will be shown in the view.

Now, I'm modifying my model and I find different situations:

  • Addition of new required fields with a database initialized, for this there are some options:
    1. Empty the table to re-populate it with records including the new information for the required fields.
    2. Define a default value for the new fields
    3. Modify the populate process of the table to add new content to the required fields.
    4. Remove the restriction to the new required fields, to do one of the optins 2 or 3, and add the restriction again.

    Personally, I prefer by the moment the option 1, but in a testing environment or a production environment, it is more recommendable the option 2.

  • Adding of relationed entities.

    I experienced some problems that didn't allowed to make the changes because of permissions, so I executed the Command Line Window with Administrator privileges, and I had no problems after that. But changing the database in my connection string to generate a clean base, I encountered problems with foreign keys.

    Adding the next code, to the tables that they could have problems of routes and circular references to update/delete data, in the .cs file of migrations can solve de problem.

    //...
        constraints: table =>
         {
          //...
           table.ForeignKey(
            // ...
             onDelete:ReferentialAction.NoAction,
             onUpdate:ReferentialAction.NoAction);
       
    1. Addition of relationed entities with more than one filed pointing to the same table.
  • Addition of controllers and views

As I'm using plain SQL queries to retrieve some data, those queries require the whole fields listing corresponding to the entity, so, as I don't need the information contained in these fields and is not my intention to create views. What I did was to put an empty value or zero to each field I required to mention.


Comentarios

Entradas populares