How to insert records in different tables with EF core in asp.net core2?

6

I have three tables, one of users that relates one to many with a table, and that one is related to the table phone_type, my calendar table has the id_agenda, user_id, phone_type_id, phone. When I create my model I only have the properties of my user

    public partial class Usuario
    {
        public Usuario()
        {
            Agenda = new HashSet<Agenda>();
        }
        [Required(ErrorMessage = "Se requiere del Curp")]
        public string Curp { get; set; }
        [Required(ErrorMessage = "Se requiere del Nombre")]
        public string Nombre { get; set; }
        [Required(ErrorMessage = "Se requiere del Apellido Paterno")]
        [Display(Name = " Apellido Paterno")]
        public string ApPat { get; set; }
        [Required(ErrorMessage = "Se requiere del Apellido Materno")]
        [Display(Name = " Apellido Materno")]
        public string ApMat { get; set; }
        [Required(ErrorMessage = "Se requiere de la contraseña")]
        [DataType(DataType.Password)]
        [Display(Name = "Contraseña")]
        public string Contrasena { get; set; }
        [Display(Name = "Tipo de Trabajador")]
        public int IdTipoTrabajor { get; set; }

        public TipoTrabajor IdTipoTrabajorNavigation { get; set; }
        public ICollection<Agenda> Agenda { get; set; }
    }

    public partial class Agenda
    {
        public int IdAgenda { get; set; }
        public string Telefono { get; set; }
        public int IdTipoTelefono { get; set; }
        public string Curp { get; set; }

        public Usuario Curp1 { get; set; }
        public TipoTelefono IdTipoTelefonoNavigation { get; set; }
    }

//modelo nuevo que hice
public class UsuarioRegister
    {

        [Required(ErrorMessage = "Se requiere del Curp")]
        public string Curp { get; set; }
        [Required(ErrorMessage = "Se requiere del Nombre")]
        public string Nombre { get; set; }
        [Required(ErrorMessage = "Se requiere del Apellido Paterno")]
        [Display(Name = " Apellido Paterno")]
        public string ApPat { get; set; }
        [Required(ErrorMessage = "Se requiere del Apellido Materno")]
        [Display(Name = " Apellido Materno")]
        public string ApMat { get; set; }
        [Required(ErrorMessage = "Se requiere de la contraseña")]
        [DataType(DataType.Password)]
        [Display(Name = "Contraseña")]
        public string Contrasena { get; set; }
        [Display(Name = "Tipo de Trabajador")]
        public int IdTipoTrabajor { get; set; }
        public TipoTrabajor IdTipoTrabajorNavigation { get; set; }
        public int IdAgenda { get; set; }
        [Required(ErrorMessage = "Se requiere del Número")]
        public string Telefono { get; set; }
        [Display(Name = "Tipo de Telefono")]
        public int IdTipoTelefono { get; set; }
        public TipoTelefono IdTipoTelefonoNavigation { get; set; }

    }

//CONTROLADOR
 public ActionResult Add(UsuarioRegister user)
        {
            var usuario = new Usuario
            {
                Curp = user.Curp,
                Nombre = user.Nombre,
                ApPat = user.ApPat,
                ApMat = user.ApMat,
                Contrasena = user.Contrasena,
                IdTipoTrabajor = user.IdTipoTrabajor,
                IdTipoTrabajorNavigation = user.IdTipoTrabajorNavigation
            };

            var telefonos = new Agenda();
            _context.Usuario.Add(usuario);
            telefonos.Curp = usuario.Curp;
            _context.Agenda.Add(telefonos);
            _context.SaveChanges();

            return View();
        }

I do not know how to use my ICollection(Agenda) to show in the view the fields to fill in the agenda along with all the user fields and how to insert them into the controller. First, it would be inserting the data of the table that are the phone that the user entered, the type of phone and the user's CURP and then the user's data in their table, but how can they be inserted together?

I am new using EF, I already look for the documentation but it only tells how to show the data together of the tables when there are already related records.

    
asked by Karla Huerta 31.01.2018 в 23:21
source

1 answer

0

First you can use LINQ (or LAMBDA) to get the data of your model from your contextDB (With only filter by your User Entity Framework will also bring you all the associated Agendas)

then you can do something like:

  CargarUsuario(){
       Usuario consulta;
      using (var context = new contextDB())
      {
          consulta = context.Usuario.Where (s => s.IdTipoTrabajor == 4).FistOrDefault();
      }
      return consulta;
   }

Then you must create an ActionResult in your controller where you get the Instance of your User object. Something like:

    public ActionResult AltaUser()
    {
        Usuario user = CargarUsuario();

        return View("AltaUser", user);
    }

Then you must create a Razor view with a static typing model and pass it the User created object (You can use the Create template of VS):

   @model EjemploAgendaUsuario_EF.Models.Usuario
   <!-- SECCION AGENDA -->

    <!-- PARA MOSTRAR ALGUN DATO DE CADA AGENDA -->
    @foreach (var item in Model.Agenda)
    {
        <div class="form-group">
            @Html.LabelFor(i => item.IdAgenda, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(i => item.IdAgenda, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(i => item.IdAgenda, "", new { @class = "text-danger" })
            </div>
        </div>
    }

The HTML Helper "EditorFor" allows you to create an editable input that you can then send to the server with the new data through a submit.

    
answered by 09.02.2018 в 17:42