Beispiel #1
0
        public void SoaTest_7_7()
        {
            LinqBooksDataContext context1 = new LinqBooksDataContext();

            context1.Log = Console.Out;

            Guid Id = new Guid("92f10ca6-7970-473d-9a25-1ff6cab8f682");

            Subject existingSubject = context1.Subject.Where(s => s.ID == Id).SingleOrDefault();

            Console.WriteLine("Starting name: {0}", existingSubject.Name);

            Subject changingSubject = new Subject {
                ID = existingSubject.ID
            };

            changingSubject.Name = @"Testing update";

            using (System.Transactions.TransactionScope ts = new System.Transactions.TransactionScope())
            {
                //Apply the changes through a mimiced service
                Subject.UpdateSubject(changingSubject);

                //Rollback the change after running the demo
            }
        }
        void FillDataSetUsingLinqToSql(LinqBooksDataSet dataSet)
        {
            var linqBooks = new LinqBooksDataContext(); //  准备LINQtoSQLDataContext

            var publisherQuery = from publisher in linqBooks.Publisher
                                 select new { publisher.ID, publisher.Name };   //  查询数据表

            var bookQuery = from book in linqBooks.Book
                            where book.PubDate.Value.Year > 1950
                            select new
            {
                book.ID,
                book.Title,
                book.Subject,
                book.Publisher,
                Price = book.Price.HasValue ? book.Price.Value : 0
            };

            foreach (var publisher in publisherQuery)
            {
                dataSet.Publisher.AddPublisherRow(publisher.ID, publisher.Name, null, null);
            }

            foreach (var book in bookQuery)
            {
                dataSet.Book.AddBookRow(book.ID, null, null, 0, book.Price, DateTime.MinValue, dataSet.Publisher.FindByID(book.Publisher), book.Subject, null, book.Title);
            }
        }
Beispiel #3
0
        public void DisconnectedTest_7_6()
        {
            LinqBooksDataContext context1 = new LinqBooksDataContext();

            context1.Log = Console.Out;

            /* Objects can only be attached to a single context at any given time.
             * This is done to avoid the potential to update child objects erroneously.
             * For the purposes of this example, we purposefully set up context1 up so that
             * it wouldn’t track the changes by setting the ObjectTrackingEnabled to false.
             * Attempting to attach an object to a second context will result in a NotSupportedException.  */
            context1.ObjectTrackingEnabled = false;

            Subject cachedSubject = context1.Subject.First();

            Console.WriteLine("Starting name: {0}", cachedSubject.Name);

            // In a real application, this object would now be cached or remoted via a web service
            // Use second context to simulate disconnected environment

            using (System.Transactions.TransactionScope ts = new System.Transactions.TransactionScope())
            {
                UpdateSubject(cachedSubject);
                Console.WriteLine("Updated name: {0}", cachedSubject.Name);
                //Rollback the change after running the demo
            }
        }
Beispiel #4
0
        public void LifecycleTest_7_5()
        {
            LinqBooksDataContext context1 = new LinqBooksDataContext();
            LinqBooksDataContext context2 = new LinqBooksDataContext();

            context1.Log = Console.Out;
            context2.Log = Console.Out;

            Guid Id = new Guid("92f10ca6-7970-473d-9a25-1ff6cab8f682");

            Subject editingSubject = context1.Subject.Where(s => s.ID == Id).SingleOrDefault();

            Console.WriteLine("Before Change:");
            ObjectDumper.Write(editingSubject);
            ObjectDumper.Write(context2.Subject.Where(s => s.ID == Id));

            editingSubject.Description = @"Testing update";

            Console.WriteLine("After Change:");
            ObjectDumper.Write(context1.Subject.Where(s => s.ID == Id));
            ObjectDumper.Write(context2.Subject.Where(s => s.ID == Id));

            context1.SubmitChanges();

            Console.WriteLine("After Submit Changes:");
            ObjectDumper.Write(context1.Subject.Where(s => s.ID == Id));
            ObjectDumper.Write(context2.Subject.Where(s => s.ID == Id));
            LinqBooksDataContext context3 = new LinqBooksDataContext();

            ObjectDumper.Write(context3.Subject.Where(s => s.ID == Id));

            //Reset values
            editingSubject.Description = "Original Value";
            context1.SubmitChanges();
        }
        public void ConcurrencyDisplayingChanges_8_6()
        {
            LinqBooksDataContext context = new LinqBooksDataContext();

            //Make some changes
            this.MakeConcurrentChanges(context);

            try
            {
                context.SubmitChanges(ConflictMode.ContinueOnConflict);
            }
            catch (ChangeConflictException)
            {
                var exceptionDetail =
                    from conflict in context.ChangeConflicts
                    from member in conflict.MemberConflicts
                    select new
                {
                    TableName     = Helpers.GetTableName(context, conflict.Object),
                    MemberName    = member.Member.Name,
                    CurrentValue  = member.CurrentValue.ToString(),
                    DatabaseValue = member.DatabaseValue.ToString(),
                    OriginalValue = member.OriginalValue.ToString()
                };
                ObjectDumper.Write(exceptionDetail);
            }
        }
        public void QueryingInheritance_8_28()
        {
            LinqBooksDataContext context = new LinqBooksDataContext();

            context.Log = Console.Out;

            //Get all users from the base instance
            Console.WriteLine("All users:");
            var query =
                from user in context.User
                select user.Name;

            ObjectDumper.Write(query);

            Console.WriteLine();
            Console.WriteLine("Authors: ");
            //Get only the authors
            var authors =
                from user in context.User
                where user is AuthorUser
                select user.Name;

            ObjectDumper.Write(authors);

            Console.WriteLine();
            Console.WriteLine("Publishers: ");
            //Get the publishers using the OfType extension method
            var publishers =
                from user in context.User.OfType <PublisherUser>()
                select user.Name;

            ObjectDumper.Write(publishers);
        }
        public void UserDefinedScalarFunctions_8_19()
        {
            LinqBooksDataContext context = this.NewContext;

            Guid?PublisherId = new Guid(@"855cb02e-dc29-473d-9f40-6c3405043fa3");

            Console.WriteLine(context.fnBookCountForPublisher(PublisherId));
        }
        public void StoredProcScalar_8_13()
        {
            Guid publisherId             = new Guid("851e3294-145d-4fff-a190-3cab7aa95f76");
            LinqBooksDataContext context = this.NewContext;

            Console.WriteLine(String.Format("Books found: {0}",
                                            context.BookCountForPublisher(publisherId).ToString()));
        }
        public void StoredProc_8_11()
        {
            Guid bookId = new Guid("0737c167-e3d9-4a46-9247-2d0101ab18d1");
            LinqBooksDataContext context = this.NewContext;
            IEnumerable <Book>   query   = context.GetBook_Custom(bookId, Thread.CurrentPrincipal.Identity.Name);

            ObjectDumper.Write(query);
        }
        private void EditingForm_Load(object sender, EventArgs e)
        {
            LinqBooksDataContext context = new LinqBooksDataContext();
            var query = from p in context.Publisher
                        select p;

            this.publisherBindingSource.DataSource = query.ToList();
        }
        public void QueryingPartialClass_8_25()
        {
            LinqBooksDataContext context = this.NewContext;
            var partialAuthors           = from author in context.Author
                                           select author;

            ObjectDumper.Write(partialAuthors);
        }
Beispiel #12
0
        public void UpdateSubject(Subject cachedSubject)
        {
            LinqBooksDataContext context = new LinqBooksDataContext();

            context.Log = Console.Out;
            context.Subject.Attach(cachedSubject);
            cachedSubject.Name = @"Testing update";

            context.SubmitChanges();
        }
        public void ConcurrencyWithTimestamp_8_3()
        {
            LinqBooksDataContext context = new LinqBooksDataContext();

            var authorToChange = (context.Author).First();

            authorToChange.FirstName = "Jim";
            authorToChange.LastName  = "Wooley";

            //Rather than committing a change, just view the SQL that would be used
            Console.WriteLine(context.GetChangeText());
        }
        private void DynamicSql(string searchName)
        {
            LinqBooksDataContext context = this.NewContext;

            string sql = @"Select ID, LastName, FirstName, WebSite, TimeStamp    " +
                         "From dbo.Author " +
                         "Where LastName = '" + searchName + "'";

            IEnumerable <Author> authors = context.ExecuteQuery <Author>(sql);

            ObjectDumper.Write(authors);
        }
        public void UpdateProcedures_8_16()
        {
            LinqBooksDataContext context = this.NewContext;
            var changingAuthor           = context.Author.FirstOrDefault <Author>();

            changingAuthor.FirstName = "Changing";
            using (System.Transactions.TransactionScope ts = new System.Transactions.TransactionScope())
            {
                context.SubmitChanges();
                //Let the transaction rollback
            }
        }
        public void DynamicSqlParameters_8_10()
        {
            string searchName = "Good' OR ''='";

            LinqBooksDataContext context = this.NewContext;
            string sql =
                @"Select ID, LastName, FirstName, WebSite, TimeStamp  " +
                "From dbo.Author " +
                "Where LastName = {0}";

            // We should actually have 0 records returned in this case.
            ObjectDumper.Write(context.ExecuteQuery <Author>(sql, searchName));
        }
        public void TransactionsSqlTransactionScope_8_8()
        {
            LinqBooksDataContext context = this.NewContext;

            this.MakeConcurrentChanges(context);

            using (System.Transactions.TransactionScope scope =
                       new System.Transactions.TransactionScope())
            {
                context.SubmitChanges(ConflictMode.ContinueOnConflict);
                scope.Complete();
            }
        }
        public void UserDefinedFunctionsInQuery_8_20()
        {
            LinqBooksDataContext context = this.NewContext;

            var query =
                from publisher in context.GetTable <Publisher>()
                select new
            {
                publisher.Name,
                BookCount = context.fnBookCountForPublisher(publisher.ID)
            };

            ObjectDumper.Write(query);
        }
Beispiel #19
0
        public void QueryExpressions_7_3()
        {
            LinqBooksDataContext context = new LinqBooksDataContext();

            var bookParam = Expression.Parameter(typeof(Book), "book");

            var query = context.Book.Where <Book>(
                Expression.Lambda <Func <Book, bool> >(
                    Expression.GreaterThan(
                        Expression.Property(bookParam, typeof(Book).GetProperty("Price")),
                        Expression.Constant(30M, typeof(decimal?))),
                    new ParameterExpression[] { bookParam }));

            ObjectDumper.Write(query);
        }
        public void UserDefinedFunctions_8_22()
        {
            LinqBooksDataContext context = this.NewContext;

            Guid publisherId = new Guid("855cb02e-dc29-473d-9f40-6c3405043fa3");
            var  query1      =
                from book in context.fnGetPublishersBooks(publisherId)
                select new
            {
                book.Title,
                OtherBookCount = context.fnBookCountForPublisher1(book.Publisher) - 1
            };

            ObjectDumper.Write(query1);
        }
        public void ConcurrencyOverwriteCurrentValues_8_5()
        {
            LinqBooksDataContext context = this.NewContext;

            //Make some changes
            this.MakeConcurrentChanges(context);

            try
            {
                context.SubmitChanges(ConflictMode.ContinueOnConflict);
            }
            catch (ChangeConflictException)
            {
                context.ChangeConflicts.ResolveAll(RefreshMode.OverwriteCurrentValues);
            }
        }
        public void DefaultConcurrencyImplementation_8_2()
        {
            LinqBooksDataContext context = this.NewContext;
            var mostExpensiveBook        = (from book in context.Book
                                            orderby book.Price descending
                                            select book).First();

            decimal discount = .1M;

            mostExpensiveBook.Price -= mostExpensiveBook.Price * discount;

            //context.SubmitChanges();

            //Rather than committing a change, just view the SQL that would be used
            Console.WriteLine(context.GetChangeText());
        }
        public void TransactionsDataContext_8_8()
        {
            LinqBooksDataContext context = this.NewContext;

            this.MakeConcurrentChanges(context);

            try
            {
                context.Connection.Open();
                context.Transaction = context.Connection.BeginTransaction();
                context.SubmitChanges(ConflictMode.ContinueOnConflict);
                context.Transaction.Commit();
            }
            catch (ChangeConflictException)
            {
                context.Transaction.Rollback();
            }
        }
        public void ConcurrencyKeepChanges_8_4()
        {
            LinqBooksDataContext context = this.NewContext;

            //Make some changes
            this.MakeConcurrentChanges(context);

            try
            {
                context.SubmitChanges(ConflictMode.ContinueOnConflict);
            }
            catch (ChangeConflictException)
            {
                context.ChangeConflicts.ResolveAll(RefreshMode.KeepChanges);
                //resubmit the merged values
                context.SubmitChanges();
            }
        }
        void FillDataSetUsingLinqToSql(DataSet dataSet)
        {
            DataTable            table;
            LinqBooksDataContext linqBooks = new LinqBooksDataContext();    //  准备LINQ to SQL 的DataContext

            var publisherQuery =
                from publisher in linqBooks.Publisher
                select new { publisher.ID, publisher.Name };

            var bookQuery = from book in linqBooks.Book
                            where book.PubDate.Value.Year > 1950
                            select new
            {
                book.ID,
                book.Title,
                book.Subject,
                book.Publisher,
                Price = book.Price.HasValue ? book.Price.Value : 0
            };

            table = new DataTable();
            table.Columns.Add("ID", typeof(Guid));
            table.Columns.Add("Name", typeof(String));

            foreach (var publisher in publisherQuery)
            {
                table.LoadDataRow(new Object[] { publisher.ID, publisher.Name }, true);
            }
            dataSet.Tables.Add(table);

            table = new DataTable();
            table.Columns.Add("ID", typeof(Guid));
            table.Columns.Add("Title", typeof(String));
            table.Columns.Add("Subject", typeof(Guid));
            table.Columns.Add("Publisher", typeof(Guid));
            table.Columns.Add("Price", typeof(decimal));

            foreach (var book in bookQuery)
            {
                table.LoadDataRow(new Object[] { book.ID, book.Title, book.Subject, book.Publisher, book.Price }, true);
            }
            dataSet.Tables.Add(table);
        }
        private void MakeConcurrentChanges(LinqBooksDataContext context)
        {
            LinqBooksDataContext context1 = this.NewContext;

            //First user raises the price of each book
            var books1 = context1.Book;

            foreach (var book in books1)
            {
                book.Price += 2;
            }

            //Second user lowers the price of each book
            var books2 = context.Book;

            foreach (var book in books2)
            {
                book.Price -= 1;
            }
            //Go ahead and submit the first changes.
            //The submit using the context passed in to this method will fail.
            context1.SubmitChanges();
        }
 public void CompiledQuery_8_23()
 {
     ObjectDumper.Write(LinqBooksDataContext.GetExpensiveBooks(30));
 }