Tags

After installed SP1 for visual studio 2008. I started playing the ADO .NET Entity. To create a entity class is very simple.
1. Add New Item
2. Select ADO .NET Entity Data Model
3. I called NorthwindEF, then follow the wizard. In this example, I only add Product and Category Tables from Nothwind database

Visual Studio will generate a NorthWindEF.edmx and code behind file

A simple example is

            using (NorthwindEFEntities context = new NorthwindEFEntities())
            {
                var query = from p in context.Products where p.ProductName.Contains("b") && p.Discontinued == false select p;

                Console.WriteLine("result 1");
                foreach (var p in query)
                {
                    p.CategoriesReference.Load();
                    Console.WriteLine("    {0}",p.Categories.CategoryName);
                    
                }
                var categories = from c in context.Categories
                                select c;

                Console.WriteLine();
                Console.WriteLine("result 2");

                foreach (Categories c in categories)
                    Console.WriteLine("    {0}", c.CategoryName);

                var query2 =
                    (from p in context.Products select p).ToList();

                //Add Product
                Console.WriteLine("Add a product");
                Products _product = new Products();

                _product.ProductName = "Pizza";
                _product.Categories = categories.First();
                _product.Discontinued = false;

                context.AddObject("Products", _product);

                context.SaveChanges();

                Console.WriteLine("New ID {0}", _product.ProductID);

                //Update Product
                _product.SupplierID = 1;

                context.SaveChanges();

                //Delete Product

                var del_prod = query2.LastOrDefault();

                context.DeleteObject( del_prod);
                context.SaveChanges();
                Console.WriteLine("Completed!");
            }

Be careful with p.CategoriesReference.Load(). If you don’t call this method. The Category object will be null

Advertisements