Include Method - MVC - working with data insertion in two tables

Asked

Viewed 1,261 times

3

I have two classes:

  • User
  • User

where Usuario possesses its id (PK) and UsuarioP owns the id (FK) of Usuario.

I am working on ASP.NET MVC 4 using Fluent API.

Classes are mapped within the project to make connection to the bank. My project is divided into controllers, services, models and views.

I have a screen Usuario using 1 field of UsuárioP.

1) How can I instill it in the class without being in the way below? (That way it doesn’t work because of the relationship, otherwise it would work):

Class User.Cs

public string login { get { return this.UsuarioP.login; } set { login = value; } }

2) On the include screen, when adding Usuario, I should also change the screen status, this status is within UsuarioP.

Controller

        public ViewResultBase Incluir(Usuario model)
        {
            if (this.ModelState.IsValid)
            {
                try
                {

                    this.Service.SalvaUsuarioP(model);
                    return this.SuccessView(true);
                }
                catch (ValidationException exception)
                {
                    base.AddValidationErrors(exception);
                    return base.PartialView(model);
                }
            }
            else
            {
                return base.PartialView(model);
            }
        }

Service

        public void SalvaUsuarioP(Usuario item)
        {
            //Salva os campos de Usuario(está funcionando perfeitamente)
            base.context.Usuario.Add(item);

            //Tentativa para salvar o login e o seu estado em UsuarioP
            foreach (var usuarioP in base.context.UsuariosP.Where(x => x.IdUsuario == item.Id))
            {
                item.login = usuarioP.Login;
                usuarioP.TipoParticipante = 3;
                base.context.UsuariosP.Add(usuarioP);
            }

        }

I tried that way, but I couldn’t. In this case, the item.login is only working because login is like [NotMapped] in Usuario.cs.

Summarizing: On the inclusion screen (Usuario) I have a field that should bring from (UsuarioP), the login.

When triggering the inclusion method, it should save the fields of the Usuario and save login to UsuarioP using IdUsuario as key and also changing login status (TipoParticipante = 3).

The mistakes I’ve already made

Invalid columm login (porque realmente `login` não existem em `Usuario`)

When debugging it includes only the fields of the Usuario, and doesn’t even go through foreach.

I don’t know how to make it work, can you help me? And if I’m not being clear, I put more details.

1 answer

3

First of all it’s important to know that Usuario has cardinality 1 to N with UsuarioP, otherwise it is impossible to answer this question.

1) How can I instate it in class without being in the way below?

public string login {get { return this.UsuarioP.login} set { login = value} }

In fact, this won’t work here because the cardinality is 1 for N, that is, you would have to define which of the N LoginYou would be changing.

2) On the include screen when adding the User items, I should also change the screen status, this status is within User.

For the same reason, this part of the service code is wrong, and for more reasons:

        //Tentativa para salvar o login e o seu estado em UsuarioP
        foreach (var usuarioP in base.context.UsuariosP.Where(x => x.IdUsuario == item.Id))
        {
            item.login = usuarioP.Login;
            usuarioP.TipoParticipante = 3;
            base.context.UsuariosP.Add(usuarioP);
        }

It doesn’t make any sense that you select several UsuarioP, then assign Login for himself. I think there is a great confusion of concepts there.

If you want to change the status of UsuarioP, the code below solves:

        foreach (var usuarioP in item)
        {
            usuarioP.TipoParticipante = 3;
            base.context.Entry(usuarioP).State = EntityState.Modified;
        }

Or if the record is new:

        foreach (var usuarioP in item)
        {
            usuarioP.TipoParticipante = 3;
            base.context.UsuariosP.Add(usuarioP);
        }

Or better yet, you can define the type default in the builder:

public UsuarioP() {
    TipoParticipante = 3;
}

Do not use the related class to make assignments until the concepts on how to work with the Entity Framework are properly set.

  • But for each added user I need to add a User with the status Typoparticipant = 3. base.context.Entry(usuarioP). State = Entitystate.Modified; I can do it ?

  • You’re adding, not editing. EntityState.Modified is for editing only.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.