C # join 3 tables using Linq?

0

I'm getting to learn C # and I'm picking up on some points.

I have 3 Tables.

Follow the models

public class Tag
{
    [Key]
    public int ID_Tag { get; set; }

    [Required(ErrorMessage = "Preencha o Nome")]
    [MaxLength(100)]
    public string Nome_Tag { get; set; }
}
public class Local
{
    [Key]
    public int ID_Local { get; set; }

    [Required(ErrorMessage = "Preencha o Nome")]
    [MaxLength(100)]
    public string Nome_Local { get; set; }
    public string Tipo_Local { get; set; }
}
public class LocTag
{
    [Key]
    public int ID_LocTag { get; set; }

    [Required]
    [ForeignKey("Tags")]
    public int ID_Tags { get; set; }

    [Required]
    [ForeignKey("Locais")]
    public int ID_Local { get; set; }

    public virtual Tag Tags { get; set; }
    public virtual Local Locais { get; set; }
}

I would like to return SQL and return it as follows.

"result":[ {  
         "Locais" :  { 
                        ID_Local, 
                        Nome_Local, 
                        Tag: [{ 
                              ID_Tag, 
                              Nome_Tag }]
                      }  
           }]

I tried in a few ways, some were very close, but not the way I intended.

var result = db.LocTag.Where(x => x.Locais.Tipo_Local == Nome).ToList();

Give me the following return:

"result": [
        {
            "Locais": {
                "ID_Local": 5,
                "Nome_Local": "NOME'
            },
            "Tags": {
                "ID_Tag": 1,
                "Nome_Tag": "NOME_TAG"
            },
            "ID_LocTag": 1,
            "ID_Tags": 1,
            "ID_Local": 5
        },....}]
    
asked by anonymous 08.11.2017 / 04:46

1 answer

0

You need to add a Select after the Where created the structure you want, below is an example with anonymous class:

var result = db.LocTag.Where(x => x.Locais.Tipo_Local == Nome)
    .Select(c =>  new { 
                          ID_Local = c.Locais.ID_Local, 
                          Nome_Local = c.Locais.Nome_Local, 
                          Tag = c.Tags 
                       }).ToList();

Here is another example where I created a class to represent the structure:

public class Locais
{
    public int ID_Local { get; set; }
    public string Nome_Local { get; set; }
    public Tag Tag { get; set; }
}

I run the same command again but in this case I fill in the above class:

 var result = db.LocTag.Where(x => x.Locais.Tipo_Local == Nome)
      .Select(c => new Locais { 
                                  ID_Local = c.Locais.ID_Local, 
                                  Nome_Local = c.Locais.Nome_Local, 
                                  Tag = c.Tags 
                              }).ToList();

I hope I have helped, any questions are available.

    
09.11.2017 / 02:00