How to instantiate primary key in another MVC class?

Asked

Viewed 713 times

2

I have the class Funcionario and Projeto. They both have their Ids.

I want to create a class ProjetoFuncionario and would like to instantiate the primary key of the two in this class.

How can I?

namespace Exercicio1.Models
{
    public class Projeto
    {
        public long id_Projeto { get; set; }
        public string nome_Projeto { get; set; }

        public List<FuncionarioModel> listaProjeto = new List<FuncionarioModel>();
    }
}

And also the class Funcionario:

public class FuncionarioModel
{
    string dataAtual = DateTime.Now.Day.ToString();

    public long id_funcionario { get; set; }
    [Required]

    [DisplayName(" Nome.: ")]
    [StringLength(40, ErrorMessage = " O Campo Nome permite apenas 40 caracteres!")]
    public string nom_funcionario { get; set; }
    [Required]
}
  • 2

    What do you mean by instantiating the primary keys? You want to make a reference of this new class to Employee and Project I suppose... for that just create a class like this: public class ProjetoFuncionarioModel { public ProjetoModel Projeto { get; set; } public FuncionarioModel Funcionario { get; set; } }.

  • i want to create a PROJECTOFUNCIONARIO class in this class i want to instantiate the working key and the design key

2 answers

2


I want to create a Projectofuncionario class...

There is no need to create a class like Projectofuncionario to express these relationships. This usually occurs when creating the database tables, then you create a table to express the relationship, but the modeling of your objects will not look exactly like you model your database.

You can work only the classes Funcionario (or FuncionarioModel as you called it) and Project itself.

...would like to instantiate the primary key of the two in this class. How can I do?

In fact, you do not have a primary key instance, because the primary key is related to the field(s) of the object(s). As we know, you create instances of objects (such as Functionary, Project, etc....).

You can create the class instance Projeto, create the instance(s) (s) of the project employee(s) and add each object Funcionario on the list. When you save the Project in the database, the framework you use (Entity Framework, Nhibernate, etc...) will make the association (saving the information in the tables of Projeto, Funcionario and ProjetoFuncionario and even generating the Ids automatically) for you.

//Instancia os objetos para exemplificar
Projeto projeto_novo = new Projeto() { nome_Projeto = "Projeto 1", lista_funcionarios = new List<Funcionario>() };
Funcionario funcionario_novo1 = new Funcionario() { nom_funcionario = "Funcionário 1" };
Funcionario funcionario_novo2 = new Funcionario() { nom_funcionario = "Funcionário 2" };

//Adiciona os funcionários na lista
projeto_novo.lista_Funcionarios.Add(funcionario_novo1);
projeto_novo.lista_Funcionarios.Add(funcionario_novo2);

One point of attention I noticed here is about the property names, because where you are using "listProject" I used "list_functionalities" in the example, just because I believe it is clearer (just suggestion).

If I haven’t answered your question yet, please enter a comment so I can help :-)

  • I understood what you meant, theoretically this was just what I needed. Thank you Renan!

1

Just complementing @Renan’s response, in his modeling a Funcionario may belong to only one Projeto and a Projeto has several Funcionarios. In another interpretation of your question, you might want a Funcionario have several Projetos, and that a Projeto may have several Funcionarios (cardinality N to N). In this case an entity is relevant ProjetoFuncionario as follows:

public class ProjetoFuncionario
{
    [Key]
    public int ProjetoFuncionarioId { get; set; }
    public int ProjetoId { get; set; }
    public int FuncionarioId { get; set; }

    public virtual Projeto Projeto { get; set; }
    public virtual Funcionario Funcionario { get; set; }
}

I take the opportunity to discuss the way you used to implement, as well as suggest some norms to make your project more organized:

namespace Exercicio1.Models
{
    [DisplayColumn("Nome")] // Esse atributo faz algumas configurações automáticas, como DropDowns, por exemplo.
    public class Projeto
    {
        [Key] // É boa prática anotar qual propriedade é chave primária.
        public long ProjetoId { get; set; } // O padrão do Entity Framework é ProjetoId ou apenas Id
        [Required] // Procure anotar campos não nulos como [Required], obrigatórios.
        public string Nome { get; set; }

        // Procure não instanciar propriedades de navegação; O Entity Framework faz isso pra você;
        // Não precisa limitar a coleção em List<>; Use ICollection<>, que permite mais recursos;
        // Procure anotar a propriedade de navegação com virtual para permitir herança.
        public virtual ICollection<ProjetoFuncionario> ProjetoFuncionarios { get; set; }
    }

    [DisplayColumn("Nome")]
    public class Funcionario
    {
        // Essa propriedade não tem necessidade de ficar aqui, então comentei.
        // public string dataAtual = DateTime.Now.Day.ToString();

        [Key]
        public long FuncionarioId { get; set; } // Novamente coloquei essa chave na convenção.
        [Required] // Atributos são sempre em cima da propriedade alvo, não embaixo como estava.
        [DisplayName(" Nome.: ")]
        [StringLength(40, ErrorMessage = "O Campo Nome permite apenas 40 caracteres!")]
        public string Nome { get; set; }

        public virtual ICollection<ProjetoFuncionario> ProjetoFuncionarios { get; set; }
    }
}
  • Gypsy, even if it is an N-N cardinality, not the need for an Entitity to represent a Link table, in this case Project can have a Icollection<Employee> and Employee Icollection<Project>.

  • @Tobymosque And if you need to express additional fields within the association, how could this be done? And if you don’t want to use Fluent API in the project for the sake of standardization, as this would be done?

  • Normally I adopt the same strategy used in the Database First model, when the relationship table has no other purpose than connecting the two tables there is no need to create a new entity.

  • @Tobymosque But here’s the thing: 90% of the sites I see around answer to that. The idea of giving a different answer that covers all cases, in my view, is more interesting.

Browser other questions tagged

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