protected void Page_Load(object sender, EventArgs e)
        {
            //Attaching Entities: http://msdn.microsoft.com/en-us/library/gg696174(v=vs.103).aspx
            //When you execute a query in a context, the returned entities are automatically attached to the context (unless you use the AsNoTracking method to execute the query). The entities are attached in the Unchanged state. You can also attach entities that are obtained from a source other than a query and are known to already exist in the database by using the System.Data.Entity.DbSet.Attach( method.
            //In the following example, the GetExistingDepartment method returns the Department entity that exists in the database. This entity could have been queried for and updated in another thread or another tier, and now needs to be attached to this context before saving changes.

            //var existingDpt = GetExistingDepartment();
            //using (var context = new SchoolEntities ())
            //{
            //    context.Departments.Attach(existingDpt);
            //    // When setting the entry state to Modified
            //    // all the properties of the entity are marked as modified.
            //    context.Entry(existingDpt).State = EntityState.Modified;
            //    context.SaveChanges();
            //}



// Tip:



//If the entity being attached has related entities, those entities are also attached to the context in the Unchanged state.



            using (var ctx = new EF360Context())
            {
                var customer = new Customer
                {
                    CustomerID   = "60861",
                    ContactTitle = "John Smith",
                    CompanyName  = "Microsoft"
                };

                ctx.Customers.Attach(customer);

                ctx.Entry(customer).State = EntityState.Modified;

                ctx.SaveChanges();
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            using (var ctx = new EF360Context())
            {
                var region     = "OR";
                var customerId = "GROWL";

                // Add new customer, Growling Dog to customers.
                var customer = new Customer {
                    CustomerID = "GROWL", CompanyName = "Growling Dog", Region = "OR"
                };
                ctx.Customers.Attach(customer);
                ctx.Entry(customer).State = EntityState.Added;
                ctx.SaveChanges();

                // Loads Orgeon customers into DbContext instance.
                // Load() forces execution of Linq query
                ctx.Customers.Where(x => x.Region == region).Load();

                // Get reference to DbSet local property, which is typeof IObservable
                var localCustomers = ctx.Customers.Local;

                // Add new customers to local DbContext instance
                localCustomers.Add(new Customer {
                    CustomerID = "MADBR", CompanyName = "Mad Bear", Region = "OR"
                });

                // Remove 'Growling Dog' from local collection, which replicates to DbContext instance
                // Find first searches context, then, if necessary, queries database
                localCustomers.Remove(ctx.Customers.Find(customerId));

                //Examine contents of context by using 'Local property' of DbContext -- no trip to DB
                //Local Collection:
                //    Growling Dog excluded as has been marked for deletion
                //    Mad Bear included as has been added, but not yet saved -- key is null
                var customersInContext =
                    localCustomers.Select(
                        x => new { x.CustomerID, x.CompanyName, EntityState = ctx.Entry(x).State.ToString() }).ToList();

                //Examine contents of database -- queries database
                //    Growling Dog marked for deletion
                //    Mad Bear not yet added
                var customersInDatabase = ctx.Customers.Where(x => x.Region == region).ToList()
                                          .Where(x => x.Region == region)
                                          .Select(x => new { x.CustomerID,
                                                             x.CompanyName,
                                                             EntityState = ctx.Entry(x).State.ToString() })
                                          .ToList();

                gvLocal.DataSource = customersInContext;
                gvLocal.DataBind();

                gvDatabase.DataSource = customersInDatabase;
                gvDatabase.DataBind();

                // Clean Up
                localCustomers.Remove(ctx.Customers.Find("MADBR"));

                ctx.SaveChanges();
                // Purposely update the underlying Carrier table so that the RowVersion value changes
                //ctx.Database.ExecuteSqlCommand(@"DELETE dbo.Customers WHERE CustomerID = 'GROWL'");
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                using (var ctx = new EF360Context())
                {
                    ctx.Database.Log = s => System.Diagnostics.Debug.WriteLine(s);

                    #region Ignore for Demo -- Create 'Before Result Set'

                    var first       = ctx.Employees.FirstOrDefault();
                    var queryBefore =
                        ctx.Employees.Where(x => x.EmployeeID == first.EmployeeID)
                        .Select(y => new { y.EmployeeID, y.LastName, y.FirstName, y.City, y.PostalCode });

                    gvBefore.DataSource = queryBefore.ToList();
                    gvBefore.DataBind();

                    #endregion

                    // Get First Employee
                    var employee = ctx.Employees.FirstOrDefault();

                    // Peak into 'state' of customer entity,
                    // as tracked by the context object
                    var state = ctx.Entry(employee).State;

                    // Peak into 'initial values' of current entity,
                    // as cached by the Context object
                    var address = ctx.Entry(employee).Property(x => x.Address).OriginalValue;
                    var city    = ctx.Entry(employee).Property(x => x.City).OriginalValue;
                    var zip     = ctx.Entry(employee).Property(x => x.PostalCode).OriginalValue;

                    // Modify postal code
                    employee.PostalCode = (int.Parse(employee.PostalCode) + 1).ToString();

                    // Modifications will have changed 'State' of entity
                    state = ctx.Entry(employee).State;

                    // Peak into 'current values' of current entity,
                    // as cached by the Context object
                    address = ctx.Entry(employee).Property(x => x.Address).CurrentValue;
                    city    = ctx.Entry(employee).Property(x => x.City).CurrentValue;
                    zip     = ctx.Entry(employee).Property(x => x.PostalCode).CurrentValue;

                    // Perform Update
                    // Call SumbitChanges() to commit our change.
                    // Based upon state of the current entity, entity framework will
                    // build appropriate Update and update both Developer and Order tables
                    ctx.SaveChanges();

                    // Check entity state again
                    state = ctx.Entry(employee).State;

                    // Call SaveChanges again -- this time no update
                    ctx.SaveChanges();

                    // Requery Category from database
                    var queryAfter =
                        ctx.Employees.Where(x => x.EmployeeID == employee.EmployeeID)
                        .Select(y => new { y.EmployeeID, y.LastName, y.FirstName, y.City, y.PostalCode });

                    gvAfter.DataSource = queryAfter.ToList();
                    gvAfter.DataBind();
                }
            }
        }
Exemplo n.º 4
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                using (var ctx = new EF360Context())
                {
                    #region Ignore for Demo -- Create 'Before Result Set'

                    var queryBefore =
                        from c in ctx.Customers.Include("Orders")
                        where c.CustomerID == "LONEP"
                        select new
                    {
                        c.Address,
                        c.City,
                        c.CompanyName,
                        c.ContactName,
                        c.PostalCode,
                        FreightCosts = c.Orders.FirstOrDefault().Freight
                    };

                    gvInsertBefore.DataSource = queryBefore.ToList();
                    gvInsertBefore.DataBind();

                    #endregion

                    // Update Code
                    // Note the use of Include() to eager join Orders with Developer
                    var customer = ctx.Customers.Include(x => x.Orders).SingleOrDefault(c => c.CustomerID == "LONEP");

                    // Peak into 'state' of customer entity,
                    // as tracked by the context object
                    var state = ctx.Entry(customer).State;

                    // Peak into 'initial values' of current entity,
                    // as tracked by the context object
                    var address = ctx.Entry(customer).Property(x => x.Address).OriginalValue;
                    var city    = ctx.Entry(customer).Property(x => x.City).OriginalValue;
                    var zip     = ctx.Entry(customer).Property(x => x.PostalCode).OriginalValue;

                    // Modify postal code
                    customer.PostalCode = (int.Parse(customer.PostalCode) + 1).ToString();

                    // Modify freight charge
                    // Get freight charge for first order
                    var freight = Convert.ToInt32(customer.Orders.FirstOrDefault().Freight);
                    // Increase frieght charge by $1.00
                    customer.Orders.FirstOrDefault().Freight = freight + 1;

                    // Modifications will have changed 'State' of entity
                    state = ctx.Entry(customer).State;

                    // Peak into 'current values' of current entity
                    address = ctx.Entry(customer).Property(x => x.Address).CurrentValue;
                    city    = ctx.Entry(customer).Property(x => x.City).CurrentValue;
                    zip     = ctx.Entry(customer).Property(x => x.PostalCode).CurrentValue;

                    // Perform Update
                    // Call SumbitChanges() to commit our change.
                    // Based upon state of the current entity, entity framework will
                    // build appropriate Update and update both Developer and Order tables
                    ctx.SaveChanges();

                    var currentCustomerZip = customer.PostalCode;

                    // Check entity state again
                    state = ctx.Entry(customer).State;

                    // Call SaveChanges again -- this time no update
                    ctx.SaveChanges();

                    #region Ignore -- Create 'After Result Set'

                    var queryAfter =
                        from c in ctx.Customers
                        where c.CustomerID == "LONEP"
                        select new
                    {
                        c.Address,
                        c.City,
                        c.CompanyName,
                        c.ContactName,
                        c.PostalCode,
                        FreightCosts = c.Orders.FirstOrDefault().Freight
                    };

                    #endregion

                    gvInsertAfter.DataSource = queryAfter.ToList();
                    gvInsertAfter.DataBind();
                }
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            using (var ctx = new EF360Context())
            {
                ctx.Database.Log = s => System.Diagnostics.Debug.WriteLine(s);

                var customerId = "LONEP";

                // Explicitly disable Lazy Loading in order to Explicitly load
                ctx.Configuration.LazyLoadingEnabled = false;

                // Demonstrate usage of explicit loading by explicitly fetching child data
                // First, fetch given customer
                var customer = ctx.Customers.FirstOrDefault(x => x.CustomerID == customerId);

                // Then, explicitly load orders for given customer.
                // Note the following code construct that explicitly loads related data:
                //    Entry() exposes information about the Customer entity from context object
                //    Collection() sets up a query to retrieve
                //       child data for the Orders navigation property
                //    Load() executes the query against database and fetches data
                ctx.Entry(customer)
                .Collection(x => x.Orders)
                .Load();

                // Reshape data to show selected properties for orders.
                // Note that this command does not execute a database command, as Customer and
                // Order data has already been fetched into the context object.
                var orders =
                    customer.Orders.Select(
                        x => new
                {
                    x.OrderID,
                    x.OrderDate,
                    x.ShipName,
                    x.Freight,
                    x.ShipCity,
                    x.ShipRegion,
                }).ToList();

                gvExplicit.DataSource = orders;
                gvExplicit.DataBind();

                // Fetch another customer
                customer = ctx.Customers.FirstOrDefault(x => x.CustomerID == "THEBI");

                // Explicit Loading with Load() provides opportunity to filter
                // related (or child) data obtained from Include() method. Normally,
                // you cannot filter child data fetched with an Include construct.

                // Explicitly load orders for given customer.
                // Note the following code construct to explicitly load related data:
                //    Entry() exposes information about the customer entity from context object
                //    Collection() sets up query to retrieve child data
                //       from Orders navigation property
                //    Query() generates a query to load child objects
                //    Include() eager loads OrderDetails
                //    Where() filters the child, or Order, data
                //    Load() executes the query against database and fetches data
                ctx.Entry(customer)
                .Collection(x => x.Orders)
                .Query()
                // Eager load OrderDetails
                .Include(y => y.OrderDetails)
                // Ability to filter child entities. Cannot normally do this from
                // an Include() method
                .Where(y => y.OrderDetails.Any(z => z.Quantity < 5))
                .Load();

                // Reshape data to show select properties for orders
                var filteredOrders =
                    customer.Orders.FirstOrDefault()
                    .OrderDetails.Select(x => new
                {
                    x.ProductID,
                    x.Quantity,
                    x.UnitPrice
                });

                gvExplicitFiltered.DataSource = filteredOrders;
                gvExplicitFiltered.DataBind();

                // Reenable Lazy Loading which is default loading behavior
                ctx.Configuration.LazyLoadingEnabled = true;
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                using (var ctx = new EF360Context())
                {
                    // Insert Data
                    // Add new "unattached" category entity
                    var category = new Category
                    {
                        CategoryName = "FoodType" + new Random().Next(100)
                    };

                    // Add new "unattached" product entity
                    var product = new Product
                    {
                        ProductName     = "NewProduct" + new Random().Next(100),
                        QuantityPerUnit = "10",
                        UnitPrice       = 10,
                    };

                    // Add new "unattached" supplier entity
                    var supplier = new Supplier()
                    {
                        CompanyName = "CompanyName" + new Random().Next(100),
                        // Get supplier type entity object
                        SupplierType = ctx.SupplierTypes.Single(x => x.ID == 1),
                    };

                    // Peak into ObjectStateManager
                    // Determine 'state' of each entity
                    var category2State = ctx.Entry(category).State;
                    var product2State  = ctx.Entry(product).State;
                    var supplier2State = ctx.Entry(supplier).State;

                    // Fun begins here
                    // Step #1: Attach new grandchild (supplier) to new child (product)
                    // Leveraging inferred relationship
                    product.Supplier = supplier;

                    // Step #2: Attach new child (product) to new parent (category)
                    // Leveraging inferred relationship
                    category.Products.Add(product);

                    // Step #3: Add object graph to context
                    // Can explicitly assign entity state of 'Added' which attaches entire
                    // graph with state of 'Added'
                    //ctx.Entry(category).State = EntityState.Added;

                    // Can ADD object graph to context which also attaches entire
                    // graph with state of 'Added'
                    ctx.Categories.Add(category);

                    ////// Demonstrate fix-up
                    ////ctx.Suppliers.Add(supplier);
                    ////ctx.Products.Add(product);
                    ////ctx.DetectChanges();

                    // Peak into ObjectStateManager
                    category2State = ctx.Entry(category).State;
                    product2State  = ctx.Entry(product).State;
                    supplier2State = ctx.Entry(supplier).State;

                    // EF generates 'insert' statements
                    // Because of inferred relationship, EF will:
                    //   1) Insert parent (Category) and grabs new categoryId
                    //   2) Insert child (Supplier) with new supplierId as FK.
                    //   3) Insert child (USAProduct) with new categoryId as FK.
                    //   4) Return Identity values for each and insert into entity objects.
                    ctx.SaveChanges();

                    // Retrieve new primary key values.
                    // EF has automatically inserted new primary keys into exsiting entities
                    var newCateoryId = category.CategoryID;
                    var newProductId = product.ProductID;
                    var supplierId   = supplier.SupplierID;

                    #region Requery database

                    var requeryDatabase =
                        // Eager loading using strongly-typed operators
                        from p in ctx.Products.Include(x => x.Category).Include(x => x.Supplier)
                        where p.ProductID >= newProductId
                        select new
                    {
                        CategoryName = category.CategoryName,
                        CategoryId   = category.CategoryID,
                        ProductName  = product.ProductName,
                        ProductId    = product.ProductID,
                        product.UnitPrice,
                        product.QuantityPerUnit,
                        SupplierType = supplier.SupplierType.Description,
                        SupplierName = supplier.CompanyName,
                    };

                    #endregion

                    gvEF.DataSource = requeryDatabase.ToList();
                    gvEF.DataBind();
                }
            }
        }