EF - Navigating through Icollection

Asked

Viewed 184 times

0

I have the following class in an application for C# practice purposes 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 class attributes Genero, I make it like a normal class: Genero.Nome, Genero.Id, etc... Now, by the class Autor, as it is a collection, I do not achieve the same result.

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

Thank you.

  • 1

    Because you have a list of Authors of the Author class, but your Book class has an Autorid?

2 answers

1


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

About the collection, ICollection does not have many ways to walk through its values. So, the best way to navigate your collection is by using a foreach (if you don’t 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 scroll 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.

  • Thank you very much Gabriel.

  • @Matheusdaumas if the answer satisfies your question, you can mark it as correct. :)

0

You will need to access item by item, and this can be done through any loop (for, foreach, while...).

Furthermore, in order to establish a 1:N ratio, it doesn’t make much sense to have a collection of authors and not have a collection with their respective Ids.

Browser other questions tagged

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