EF - Navigate through ICollection

0

I have the following class in a C # practice application with EntityFramework:

public class Livro
{
    public Livro()
    {
        Autor = new HashSet<Autor>();            
    }

    public int Id { get; set; }
    public string Titulo { get; set; }
    public int ISBN { get; set; }
    public int GeneroId { get; set; }
    public int AutorId { get; set; }

    public virtual ICollection<Autor> Autor { get; set; }
    public virtual Genero Genero { get; set; }
}
When I want to access the attributes of the Genero class, I do it as if it were a normal class: Genero.Nome , Genero.Id , etc ... Now, for class Autor , as it is a collection, I can not the same result.

I would like to know how to navigate through ICollection<Autor> Autor to access its attributes.

Thank you.

    
asked by anonymous 15.03.2018 / 01:53

2 answers

1

As you said, your 1-to-N relationship is wrong. The foreign key should be within Author, since it is the Author who should know which book to which it relates.

About the collection, ICollection does not have many ways to go through its values. So, the best way to navigate your collection is to use a foreach (if you do not want to go all the way, you can use a for ):

foreach(var prop in Author) {
    prop.Titulo = "Teste";
}

There is the LINQ API that helps a lot to make queries within collections similar to the solutions you find in SQL language. If you want a specific value you can search it using FirstOrDefault:

var meuAutor = Author.FirstOrDefault(prop => prop.Id == 1);
return meuAutor.Titulo; //Caso ele não ache, o valor Default é null e vai dar exceção.

If you just want to go through your list, the foreach is more than enough. If you want to make larger manipulations in your collection, you can convert your ICollection to an IList and manipulate it using index.

    
15.03.2018 / 13:09
0

It will be necessary to access item by item, and this can be done through any loop of for, foreach, while ...).

Furthermore, in order to establish a 1: N relationship, it does not make much sense to have a collection of authors and not have a collection with their respective IDs.

    
15.03.2018 / 12:36