Search code examples
c#entity-frameworklinq-to-entities

How get data from C# Model using SQl, EF and linQ


Below are 3 classes that I have built and I want to get and loop data from table RestaurantVersion calling from Class 3. Can someone help me out to accomplish this? I am very new to C# and trying to learn but this part is somewhat confusing to me. Thank you!

Class 1

Class 2

Class 3


Solution

  • You can do it like this

    public class ProcessProofs
    {
        public void Process()
        {
            var context = new RestaurantVersion();
    
            List<DbRestaurantVersion> restaurantVersions = context.RestaurantVersions.ToList();
    
            foreach (DbRestaurantVersion item in restaurantVersions)
            {
                //process item
            }
        }
    }
    

    You can build complex Linq query to retrieve data that you need. DbSet doesn't contain any data at all but when you call ToList or iterating through DbSet collection Entity Framework builds sql query based on Linq expression, sends it to database and retrieves data mapped to classes.