Table relationship - EF

Asked

Viewed 210 times

4

Good Afternoon!

I have the "Service Order" and "Attachment" tables. In my "Service Order" table, I want to be able to attach the scanned service order and be able to attach pictures of the equipment.

Work order

[Table("OrdemDeServico")]
public class OrdemDeServico
{
    public OrdemDeServico()
    {

        OrdemEscaneada = new Anexo();
        FotosDoEquipamento = new List<Anexo>();
    }


    [Key]
    public int Id { get; set; }

    public int? OrdemEscaneada_Id { get; set; }

    [Display(Name="Ordem de Serviço")]
    [ForeignKey("OrdemEscaneada_Id")]
    public virtual Anexo OrdemEscaneada { get; set; }
    public virtual List<Anexo> FotosDoEquipamento { get; set; }
...

Now for the Annex

public class Anexo
{

    [Key]
    public int Id { get; set; }

    [StringLength(80)]
    public string Nome { get; set; }

    public Byte[] Arquivo { get; set; }

}

I can add and remove the scanned order easily. I know it would be better to put the relationship in the table "Attachment", but I can’t do it in a good way. I tried the following:

 public int? FotosDoEquipamento_Id { get; set; }

    [ForeignKey("FotosDoEquipamento_Id")]
    public virtual OrdemDeServico FotosDoEquipamento { get; set; }

Only that still creating "Ordemdeservico_id", must be the relationship on account of the orderSampled, but the foreign key is in another table, and I thought it would not give problem.

The point is that I don’t know how to add the photos. I didn’t want to create another table just for this, since this one already has what I need.

The table design created by the system:

inserir a descrição da imagem aqui

  • maybe it’s me, but I don’t quite understand. OrdemDeServico has a Anexo, Anexo has a OrdemDeServico. 1:N mapping should work as you did. What is not working?

  • Now I saw that there are two relations between the entities. That must be what is causing the problem. Maybe someone can, but I could only find out by running the code. If you can, put here the database schema generated by your code.

  • That’s right. Ordemdeservico in an Orderly property of type Attachment, and other Photosdoequipment of type attachment as well. This got a little confusing on how to do relationship.

  • I want to use the same table "Attachment" both to save the Ordemescaneada(One unit), and Photosescaneadas(0 or x units).

1 answer

2

Your code is quite out of standard, and this makes the Entity Framework may not work properly.

I’ll start with the entity OrdemDeServico:

[Table("OrdemDeServico")]
public class OrdemDeServico
{
    public OrdemDeServico() // Este construtor não precisa.
    {
        // Estas inicializações não precisam.
        // O Entity Framework inicializa elas para você.
        OrdemEscaneada = new Anexo();
        FotosDoEquipamento = new List<Anexo>();
    }

    [Key]
    public int Id { get; set; }
    // Esta chave estrangeira está fora do padrão. 
    // O correto é OrdemEscaneadaId.
    public int? OrdemEscaneada_Id { get; set; }

    [Display(Name="Ordem de Serviço")]
    [ForeignKey("OrdemEscaneada_Id")] // Isto aqui não é necessário.
    public virtual Anexo OrdemEscaneada { get; set; }
    // List implementa ICollection. A recomendação é usar
    // a interface, até para que você tenha mais opções na 
    // hora de iterar os objetos.
    public virtual List<Anexo> FotosDoEquipamento { get; set; }
...

It’s not incorrect, but it needs to improve.

Already Anexo I can’t say the same. You defined relationships incorrectly. If Anexo may belong to an order of service, but at the same time may contain another order of service (as it is a scanned order), the relationship becomes a paradox. By the Entity Framework convention, if OrdemDeServico contains a "Scan Order", so "Scan Order" does not need to reference OrdemeServico, but "Scanned Order" remains a Anexo, which forces the table to have a key.

This is not simple to solve and calls for a mixed approach. First, modify Anexo forever belong to a OrdemDeServico:

public class Anexo
{
    [Key]
    public int Id { get; set; }
    public int OrdemServicoId { get; set; }

    [StringLength(80)]
    public string Nome { get; set; }

    public Byte[] Arquivo { get; set; }

    public virtual OrdemDeServico OrdemDeServico { get; set; }
}

Second of all, let OrdemDeServico in the pattern:

[Table("OrdemDeServico")]
public class OrdemDeServico
{
    [Key]
    public int Id { get; set; }   
    public int? OrdemEscaneadaId { get; set; }

    [Display(Name="Ordem de Serviço")]
    public virtual Anexo OrdemEscaneada { get; set; }
    public virtual ICollection<Anexo> FotosDoEquipamento { get; set; }
...

In your context class, define the following method, using the Fluent API:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<OrdemDeServico>().HasRequired(x => x.OrdemEscaneada)
        .WithMany()
        .HasForeignKey(x => x.OrdemEscaneadaId)
        .WillCascadeOnDelete(false);

    modelBuilder.Entity<Anexo>()
        .HasRequired(x => x.OrdemDeServico)
        .WithMany(x => x.FotosDoEquipamento)
        .HasForeignKey(x => x.OrdemDeServicoId);

    ...
}
  • I tried to do with . Hasoptional() and generates error, because I do not want it to be mandatory, because in the first registration you will have nothing, only after.

  • Error:One or more validation errors Were Detected During model Generation:DAL.Ordemdeservico_ordersmescaneada: Multiplicity Conflicts with the referential Constraint in Role 'Ordemdeservico_ordersmescane_target' in Relationship 'Ordemdeservico_ordeordeordersmescaneada'. Because all of the properties in the Dependent Role are non-nullable, multiplicity of the Principal Role must be '1'. DAL.Anexo_ordemdeservico: :

  • Multiplicity Conflicts with the referential Constraint in Role 'Anexo_ordemdeservico_target' in Relationship 'Anexo_ordemdeservico'. Because all of the properties in the Dependent Role are non-nullable, multiplicity of the Principal Role must be '1'.

  • @Euripedesbarsanulfodearaujo Can you please edit your question and place as is the code so far?

  • I’m thinking of creating a new table just for photos, this turning too gambiarra. What’s your opinion?

  • @Euripedesbarsanulfodearaujo My opinion is that this should be separated from the beginning.

  • It is that I use this table to guard vouchers of payments, and I saw that to save a service order would not give any problem, but now with scanned photos of the equipment this generating headache. I will follow your advice and separate. I think I will create one just for proof, another for order, and another for photos, is better right? For "health" of the bank would not be better less table possible? But I see that can not hurt the "clarity" of the tables also right? Your opinion?

  • 1

    @Euripedesbarsanulfodearaujo I see how interesting the separation when it starts to disturb the modeling, which is your case. I think the number of tables does not influence the "health" of the bank. What influences are tables with many lines.

  • 1

    Thank you for your opinion ... I will do this. ?

Show 4 more comments

Browser other questions tagged

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