I
I
IvanSerachev2022-01-24 15:29:23
C++ / C#
IvanSerachev, 2022-01-24 15:29:23

How to define a list?

I am solving a learning problem using LINQ. I created a small local database through code, after which the task is to write a couple of methods for counting and displaying data by condition. The latter was difficult. The goal is the following - there are two tables Units and Capacities. You need to display all units belonging to a certain capacity.

I manage to display all the capacities belonging to the unit, but when I try to display it the other way around, the compiler swears at the lack of a reference to the object. If I understand correctly, then it is necessary to somehow define List in advance ... But how? It seems that it is already defined when creating the Unit ...

This is how the tables are defined:

public class Unit
    {
        public int Id { get; set; }
        public string UnitName { get; set; }
        public ICollection<Tank> Tanks { get; set; }

        public Unit()
        {
            Tanks = new List<Tank>();
        }
        public Factory Factory { get; set; }

    }
    public class Tank
    {
        public int Id { get; set; }
        public string TankName { get; set; }
        public double Volume { get; set; }
        public int Capacity { get; set; }
        public Unit Unit { get; set; }
    }
// Сам метод:
       public static void FindUnit()
        {
            
            using(var db=new FactoryContext())
            {
                
                var tanks = db.Tanks.Where(tank => tank.TankName == "Резервуар 1");       
                         
                foreach (Tank tank in tanks)
                {
                    Console.WriteLine(tank.Unit.UnitName);
                }
                      
            }
        }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
@
@insighter, 2022-01-26
@IvanSerachev

You need to create all collections

public ICollection Tanks { get; set; } = new List<Tank>;

etc..

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question