예제 #1
0
        static void Main(string[] args)
        {
            //good for desktop applicatios wpf etc...
            //var context = new PlutoContext();
            //var authors = context.Authors.ToList();// A Dictionary for Grids or comboBoxes
            //var author = context.Authors.Single(a => a.Id == 1);
            //var Course = new Course
            //{
            //    Name = "New Course2",
            //    Description = "New Description2",
            //    FullPrice = 20.95f,
            //    Level = 1,
            //    Author = author
            //};
            //context.Courses.Add(Course);
            //context.SaveChanges();

            // Better for MVC and webApplications
            var context = new PlutoContext();
            var Course  = new Course
            {
                Name        = "New Course 3",
                Description = "New Description 3",
                FullPrice   = 20.95f,
                Level       = 1,
                AuthorId    = 1
            };

            context.Courses.Add(Course);
            context.SaveChanges();
        }
        private static void Queries(PlutoContext ctx)
        {
            Console.WriteLine("\n---Group example---");
            var groupQuery = ctx.Courses.GroupBy(c => c.Level).ToList();

            foreach (var item in groupQuery)
            {
                Console.WriteLine(string.Format("{0} ({1})", item.Key, item.Count()));
                item.ToList().ForEach(i => Console.WriteLine("-" + i.Name));
            }

            Console.WriteLine("\n---Join example---");
            var joinQuery = ctx.Courses.Join(ctx.Authors, c => c.AuthorId, a => a.Id,
                                             (c, a) => new { CourseName = c.Name, AuthorName = a.Name });

            joinQuery.ToList()
            .ForEach(j => Console.WriteLine(string.Format("{0} ({1})", j.AuthorName, j.CourseName)));

            Console.WriteLine("\n---GroupJoin example---");
            var groupJoinQuery = ctx.Authors.GroupJoin(ctx.Courses, a => a.Id, c => c.AuthorId,
                                                       (a, courses) => new { AuthorName = a.Name, CoursesCount = courses.Count() });

            groupJoinQuery.ToList()
            .ForEach(gj => Console.WriteLine(string.Format("{0} ({1})", gj.AuthorName, gj.CoursesCount)));
        }
예제 #3
0
        private static void linqExampleOne()
        {
            var context = new PlutoContext();

            // LINQ syntax;
            var query =
                from c in context.Courses
                where c.Name.Contains("c#")
                orderby c.Name
                select c;

            foreach (var course in query)
            {
                Console.WriteLine(course.Name);
            }


            Console.WriteLine("-------------");

            // Extension methods;
            var courses = context.Courses
                          .Where(c => c.Name.Contains("c#"))
                          .OrderBy(c => c.Name);

            foreach (var course in courses)
            {
                Console.WriteLine(course.Name);
            }
        }
        private static void AddingObjects()
        {
            var context = new PlutoContext();

            // Method 1, Using an existing object in context
            //var authors = context.Authors.ToList();
            //var author = context.Authors.Single(a => a.Id == 1);

            // Method 3
            var author = new Author()
            {
                Id = 1, Name = "Kubing"
            };

            context.Authors.Attach(author);

            var course = new Course()
            {
                Name        = "New Course",
                Description = "New Description",
                FullPrice   = 19.95f,
                Level       = 1,
                //Author = author // Method 1
                //AuthorId = 1 // Method 2, Using foreign key properties
                Author = author // Method 3, not recommend
            };

            context.Courses.Add(course);

            context.SaveChanges();
        }
예제 #5
0
        private static void ExampleDeferredExecution()
        {
            // Queries are not executed at the time you create them;

            // Query executed when:
            // - Iterating over query variable;
            // - Calling ToList, ToArray, ToDictionary
            // - Calling First, Last, Single, Count, Max, Min, Average

            var context = new PlutoContext();

            var courses  = context.Courses;
            var filtered = courses.Where(c => c.Level == 1);
            var sorted   = filtered.OrderBy(c => c.Name);

            var courses2 = context.Courses.Where(c => c.Level == 1).OrderBy(c => c.Name);

            foreach (var c in courses)
            {
                Console.WriteLine(c.Name); // the query will be executed here; you can use SQL Profiler to see it;
            }
            Console.WriteLine("-------------");

            // IsBeginnerCourse is a custom property;
            // immediate execution;
            // Without "ToList()" will thrown an error;
            var courses3 = context.Courses.ToList().Where(c => c.IsBeginnerCourse == true);

            foreach (var c in courses3)
            {
                Console.WriteLine(c.Name);
            }
        }
        static void Main(string[] args)
        {
            var context = new PlutoContext();

            // Add an object
            context.Authors.Add(new Author {
                Name = "New Author"
            });

            // Update an object
            var author = context.Authors.Find(3);

            author.Name = "Updated";

            // Remove an object
            var another = context.Authors.Find(4);

            context.Authors.Remove(another);

            var entries = context.ChangeTracker.Entries();

            foreach (var entry in entries)
            {
                Console.WriteLine(entry.State);
            }
        }
        private static void ChangeTracker()
        {
            var context = new PlutoContext();

            // Add an object
            context.Authors.Add(new Author()
            {
                Name = "New Author"
            });

            // Update an object
            var author = context.Authors.Find(3);

            author.Name = "Updated";

            // Remove an object
            var another = context.Authors.Find(4);

            context.Authors.Remove(another);

            var entries = context.ChangeTracker.Entries();

            foreach (var entry in entries)
            {
                entry.Reload(); // Reload Data from DB
                Console.WriteLine(entry.State);
            }
        }
예제 #8
0
        static void Main(string[] args)
        {
            var context = new PlutoContext();

            // Linq syntax
            var query = from course in context.Courses
                        where course.Name.Contains("c#")
                        orderby course.Name
                        select course;

            foreach (var course in query)
            {
                System.Console.WriteLine(course.Name);
            }

            // Extension methods
            var courses = context.Courses
                          .Where(c => c.Name.Contains("c#"))
                          .OrderBy(c => c.Name);

            foreach (var course in courses)
            {
                System.Console.WriteLine(course.Name);
            }
        }
예제 #9
0
        private static void ExampleWorkingWithChangeTracker()
        {
            var context = new PlutoContext();

            // Add an object
            context.Authors.Add(new Author {
                Name = "New Author 1"
            });

            // Update an object
            var author = context.Authors.Find(6);

            author.Name = "Updated";

            // Remove an object
            var another = context.Authors.Find(6);

            context.Authors.Remove(another);

            var entries = context.ChangeTracker.Entries();

            foreach (var entry in entries)
            {
                // Reload this can sometimes be useful if you have edited an entry, but you change your mind and you want
                // to reload it from the database;
                // entry.Reload();

                // can debug to edit the values if you want and see the properties;
                Console.WriteLine(entry.State);
            }
        }
예제 #10
0
        private static void Main(string[] args)
        {
            var context = new PlutoContext();
            //LINQ syntax
            var query =
                from c in context.Courses
                where c.Name.Contains("C#")
                orderby c.Name
                select c;

            foreach (var course in query)
            {
                Console.WriteLine(course.Name);
            }

            //// Extension methods
            //var courses = context.Courses
            //    .Where(c => c.Name.Contains("C#"))
            //    .OrderBy(c => c.Name);

            //foreach (var cource in courses)
            //{
            //    Console.WriteLine(cource.Name);
            //}
        }
예제 #11
0
        private static void ExampleOtherMethodsNotSupportedByLINQSyntax()
        {
            var context = new PlutoContext();

            // Partitioning; - This is pretty useful when you want to return a page of records;
            var courses = context.Courses.Skip(10).Take(10);

            // Element Operators;
            //context.Courses.First...
            context.Courses.OrderBy(c => c.Level).FirstOrDefault(c => c.FullPrice > 100);
            // context.Courses.Last   - The last method cannot be applied when you are working with a database like SQL server;
            // in SQL we don't have an operator to get the last record in a table, so if you want the last record you need to
            // sort them in a descending way and then select the first record;
            context.Courses.SingleOrDefault(c => c.Id == 1); // this is used to return only a single object;

            // Quantifying;
            var allAbove10Dollars = context.Courses.All(c => c.FullPrice > 10);

            context.Courses.Any(c => c.Level == 1);

            // Aggregating;
            var count = context.Courses.Count();

            context.Courses.Max(c => c.FullPrice);
            context.Courses.Min(c => c.FullPrice);
            context.Courses.Average(c => c.FullPrice);

            var count2 = context.Courses.Where(c => c.Level == 1).Count();
        }
예제 #12
0
        private static void Main(string[] args)
        {
            var context = new PlutoContext();
            //LINQ syntax
            var query =
                from c in context.Courses
                where c.Name.Contains("C#")
                orderby c.Name
                select c;

            foreach (var course in query)
            {
                Console.WriteLine(course.Name);
            }

            //// Extension methods
            //var courses = context.Courses
            //    .Where(c => c.Name.Contains("C#"))
            //    .OrderBy(c => c.Name);

            //foreach (var cource in courses)
            //{
            //    Console.WriteLine(cource.Name);
            //}
        }
        static void Main(string[] args)
        {
            var context = new PlutoContext();

            //// LINQ syntax
            //var query =
            //    from c in context.Courses
            //    where c.Name.Contains("c#")
            //    orderby c.Name
            //    select c;
            //foreach (var course in query)
            //    Console.WriteLine(course.Name);

            //// Extension methods

            //    .Where(c => c.Name.Contains("c#"))
            //    .OrderBy(c => c.Name);

            //foreach (var course in courses)
            //    Console.WriteLine(course.Name);

            //LINQ Syntax


            //Restriction
            //var query =
            //    from c in context.Courses
            //    where c.Level == 1 && c.Author.Id == 1
            //    select c;

            //Ordering
            //var query =
            //    from c in context.Courses
            //    where c.Author.Id == 1
            //    orderby c.Level descending, c.Name
            //    select c;

            //Projection
            //var query =
            //    from c in context.Courses
            //    where c.Author.Id == 1
            //    orderby c.Level descending, c.Name
            //    select new { Name = c.Name, Author = c.Author.Name };

            //Grouping
            var query =
                from c in context.Courses
                group c by c.Level
                into g
                select g;

            foreach (var group in query)
            {
                Console.WriteLine("{0} ({1})", group.Key, group.Count());

                //foreach (var course in group)
                //    Console.WriteLine("\t{0}", course.Name);
            }
        }
예제 #14
0
 static void UseAnonymObject()
 {
     var context = new PlutoContext();
     var query   =
         from c in context.Courses
         where c.Name.Contains("C#")
         orderby c.Name
         select new { Name = c.Name, Id = c.Id };
 }
예제 #15
0
        static void Main(string[] args)
        {
            var context = new PlutoContext();
            var course  = context.Courses.Find(10); //same for Single(c=>c.Id == 4)

            course.Name        = "New Name";
            course.Description = "Updating by me";
            course.AuthorId    = 2;
            context.SaveChanges();
        }
예제 #16
0
        static void Main(string[] args)
        {
            var context = new PlutoContext();
            var courses = context.Courses.Include(c => c.Author).ToList();

            foreach (var course in courses)
            {
                Console.WriteLine("{0} by {1}", course.Name, course.Author.Name);
            }
        }
        private static void LinqExtensionMethod()
        {
            var context = new PlutoContext();

            var tags = context.Courses
                .Where(c => c.Level == 1)
                .OrderByDescending(c => c.Name)
                .ThenByDescending(c => c.Level)
                .SelectMany(c => c.Tags)
                .Distinct();

            //foreach (var t in tags)
            //    Console.WriteLine(t.Name);

            // Group
            var groups = context.Courses.GroupBy(c => c.Level);

            foreach (var group in groups)
            {
                Console.WriteLine($"Key: {group.Key}");

                foreach (var course in group)
                {
                    Console.WriteLine($"\t{course.Name}");
                }
            }

            // Inner Join
            var innerJoin = context.Courses.Join(context.Authors
                , c => c.AuthorId
                , a => a.Id
                , (course, author) => new
                    {
                        CourseName = course.Name,
                        AuthorName = author.Name
                    });

            // Group Join
            var groupJoin = context.Authors.GroupJoin(context.Courses
                , a => a.Id
                , c => c.AuthorId
                , (author, courses) => new
                    {
                        AuthorName = author.Name,
                        Courses = courses
                    });

            // Cross Join
            var crossJoin = context.Authors.SelectMany(a => context.Courses
                , (author, course) => new
                    {
                        AuthorName = author.Name,
                        CourseName = course.Name
                    });
        }
예제 #18
0
        public static void Query(PlutoContext context)
        {
            Console.WriteLine("DeferredExecution.Query");

            var courses = context.Courses;

            foreach (var course in courses)
            {
                Console.WriteLine(course.Name);
            }
        }
        private static void UpdatingObjects()
        {
            var context = new PlutoContext();

            var course = context.Courses.Find(4); // Single(c => c.Id == 4)

            course.Name     = "New Name";
            course.AuthorId = 2;

            context.SaveChanges();
        }
예제 #20
0
        private static void ExampleExplicitLoading()
        {
            // Here we get the code of Eager Loading, and modified the code to use Explicit Loading;

            // You can run the application and see the queries in SQL Profiler;

            var context = new PlutoContext();

            // The Include was removed, and this is going to simplify my query, because EF is not
            // going to join the Authors table with the Courses table;
            // And then we need to explicity load the courses for this author; and this is what we call Explicit Loading;
            var author = context.Authors.Single(a => a.Id == 1);

            // There are two ways to do Explicit Loading:

            // MSDN way (this only works for single entries - for example, here he have only one author object):
            context.Entry(author).Collection(a => a.Courses).Load();

            // Other way (Mosh way):
            context.Courses.Where(c => c.AuthorId == author.Id).Load();

            foreach (var course in author.Courses)
            {
                Console.WriteLine("{0}", course.Name);
            }

            // With the Explicit Loading we can simplify the complex query that is result of too many
            // includes and too much Eager Loading; Of course, we're going to end up with multiple round
            // trips to the database, but sometimes this can be more efficient than running a huge query
            // on the database;

            // But Explicit Loading also has another benefit: we can apply filters to the related objects:

            // MSDN Way:
            context.Entry(author).Collection(a => a.Courses).Query().Where(c => c.FullPrice == 0).Load();

            // Other way (Mosh way):
            context.Courses.Where(c => c.AuthorId == author.Id && c.FullPrice == 0).Load();

            // ------------------------------------------------------------------------------

            var authors = context.Authors.ToList();

            // Prefer to use the second approach - the Mosh way - because it's simpler and it's more flexible;
            // for example, to get the free courses for these authors, we cannot use the MSCN approach, because
            // if I call context.Entry, I cannot pass the authors object, because the Entry method is used to
            // reference only a single entry, a single object;
            //context.Entry()...

            // with the other approach, see:
            var authorIds = authors.Select(a => a.Id);

            context.Courses.Where(c => authorIds.Contains(c.AuthorId) && c.FullPrice == 0).Load();
        }
예제 #21
0
        public static void Pagination(PlutoContext context)
        {
            Console.WriteLine("ExtensionMethods.Pagination");
            Console.WriteLine();

            var courses = context.Courses.OrderBy(c => c.Name).Skip(2).Take(2);

            foreach (var course in courses)
            {
                Console.WriteLine("{0}, {1}", course.Author.Name, course.Name);
            }
        }
예제 #22
0
        public static void LazyLoading(PlutoContext context) // avoid lazy loading in web applications
        {
            Console.WriteLine("Lazy loading");
            Console.WriteLine();

            var course = context.Courses.Single(c => c.Id == 2);

            foreach (var tag in course.Tags)
            {
                Console.WriteLine(tag.Name);
            }
        }
예제 #23
0
        static void Main(string[] args)
        {
            var context = new PlutoContext();

            var courses = context.Courses.Single(x => x.Id == 2);

            foreach (var item in courses.Tags)
            {
                Console.WriteLine(item.Name);
            }
            Console.ReadKey();
        }
예제 #24
0
        static void Main(string[] args)
        {
            using (var ctx = new PlutoContext())
            {
                var authors   = ctx.Authors.ToList();
                var authorIds = authors.Select(a => a.Id);

                //load all of the courses whose authors are contained in the list of authors we brought back
                //and which are also free.
                ctx.Courses.Where(c => authorIds.Contains(c.AuthorId) && c.FullPrice == 0).Load();
            }
        }
예제 #25
0
        static void UseSqlProfiler()
        {
            var context = new PlutoContext();

            var courses = context.Courses;
            var filtred = courses.Where(c => c.Level == 1);
            var sorted  = courses.OrderBy(c => c.Name);

            foreach (var course in filtred)
            {
                Console.WriteLine(course.Name);
            }
        }
예제 #26
0
        public static void UsingWhere(PlutoContext context)
        {
            Console.WriteLine("ExtensionMethods.UsingWhere");
            Console.WriteLine();

            var courses = context.Courses
                          .Where(c => c.Level == 1);

            foreach (var course in courses)
            {
                Console.WriteLine(course.Name);
            }
        }
예제 #27
0
        static void Main(string[] args)
        {
            var context    = new PlutoContext();
            var authors    = context.Authors.ToList();
            var authorsIds = authors.Select(a => a.Id);

            context.Courses.Where(c => authorsIds.Contains(c.AuthorId) && c.FullPrice == 0).Load();

            foreach (var item in context.Courses)
            {
                Console.WriteLine("{0}", item.Author.Name);
            }
        }
예제 #28
0
        static void Main(string[] args)
        {
            var context = new PlutoContext();
            var querru  =
                from a in context.Authors
                join c in context.Courses on a.Id equals c.AuthorId into g
                select new { authorName = a.Name, Courses = g.Count() };

            foreach (var c in querru)
            {
                System.Console.WriteLine(c.authorName + ": " + c.Courses);
            }
        }
예제 #29
0
        static void UseLinq()
        {
            var context = new PlutoContext();
            var query   =
                from c in context.Courses
                where c.Name.Contains("C#")
                orderby c.Name
                select c;

            foreach (var course in query)
            {
                Console.WriteLine("Data is {0},{1}", course.Id, course.Name);
            }
        }
예제 #30
0
파일: Program.cs 프로젝트: Burnishtech/2019
        static void Main(string[] args)
        {
            PlutoContext plutoContect = new PlutoContext();
            //   var Courses = plutoContect.Courses.Where(C => C.Name.Contains("C#")).OrderBy(S=>S.Name).ThenByDescending(C=>C.Name);//Join(Author,A=>A.AuthorId ,C=>C.)
            var Courses = plutoContect.Courses.Where(C => C.Name.Contains("C#")).OrderBy(S => S.Name).ThenByDescending(C => C.Name);//Join(Author,A=>A.AuthorId ,C=>C.)

            foreach (var course in Courses)
            {
                //Console.WriteLine($"Your result: {num1} - {num2} = " + (num1 - num2));

                Console.WriteLine("The Course List {0}", course.Name);
                Console.Read();
            }
        }
예제 #31
0
        //Load related Objects
        static void UseExplicitloding()
        {
            var context = new PlutoContext();

            var author = context.Authors.Single(a => a.Id == 2);

            context.Courses.Where(c => c.AuthorId == author.Id && c.FullPrice == 0).Load(); //add filter for more more efficiently


            foreach (var course in author.Courses)
            {
                Console.WriteLine("{0},{1}", course.Author.Name, course.Name);
            }
        }