vsug day 2010 summer - using ado.net entity framework

of 75 /75
ADO.NET Entity Framework を使いこなそう 福井 厚 ( Twitter: @afukui ) VSUG運営委員 Microsoft Certified Architect Microsoft Regional Director Microsoft MVP for Visual C# VSUG DAY 2010 Summer

Author: atsushi-fukui

Post on 15-Jan-2015

5.741 views

Category:

Technology


4 download

Embed Size (px)

DESCRIPTION

This presentataion slide describes Microsoft.NET Framework 4 ADO.NET Entity Framework and was used for VSUG Day 2010 Summer in Japan. VSUG (Visual Studio Users Group)

TRANSCRIPT

  • 1. VSUG DAY 2010 SummerADO.NET Entity Framework ( Twitter: @afukui ) VSUG Microsoft Certified ArchitectMicrosoft Regional Director Microsoft MVP for Visual C#

2. Group Manager / CTO Architect Visual Studio User Group Microsoft Certified Architect (MCA) Microsoft Regional Director Microsoft MVP for Visual Developer C# Blog: http://www.users.gr.jp/blogs/fukui/ Twitter: @afukuiVSUG DAY 2010.05.09 3. VSUG DAY 2010.05.09 4. Agenda ADO.NET Entity FrameworkEDMEntity Domain ModelObjectServicesN VSUG DAY 2010.05.09 5. RDB VSUG DAY 2010.05.09 6. DB VSUG DAY 2010.05.09 7. VSUG DAY 2010.05.09 8. Entity Framework ADO.NET EDMVSUG DAY 2010.05.09 9. Entity Framework ArchitectureObject Services Entity Domain Model ObjectContext ObjectQuery Data Class CSDLEntityClient EntityConnectionMSLEntityCommand EntityDataReader SSDL VSUG DAY 2010.05.09 10. VSUG DAY 2010.05.09 11. EDMEntity Domain Model () VSUG DAY 2010.05.09 12. CSDLEDMDSLDomain Specific Language1 SSDL MSL VSUG DAY 2010.05.09 13. Entity Data Model Entity Data Model Entity Data Model 2 End End End () () VSUG DAY 2010.05.09 14. Entity Data Model Binary MaxLengthFixedLengthNullableDefault Booleantrue false NullableDefault Byte 8 PrecisionNullableDefault DateTime PrecisionNullableDefault DateTimeOffset GMT PrecisionNullableDefault() Decimal PrecisionNullableDefault Double 15 PrecisionNullableDefault Float7 PrecisionNullableDefaultVSUG DAY 2010.05.09 15. Entity Data Model Guid 16 PrecisionNullableDefault Int16 16 PrecisionNullableDefault Int32 32 PrecisionNullableDefault Int64 64 PrecisionNullableDefault SByte 8 PrecisionNullableDefault String UnicodeFixedLengthMaxLength CollationPrecisionNullableDefault Time PrecisionNullableDefault VSUG DAY 2010.05.09 16. End End End 1, 0..1, *) End CASCADE ON DELETE VSUG DAY 2010.05.09 17. ADO.NET Entity Data ModelVSUG DAY 2010.05.09 18. VSUG DAY 2010.05.09 19. Object Services Entity Framework (CSDL) ObjectContext EntityObject ComplexObject ObjectStateManager VSUG DAY 2010.05.09 20. ObjectQuery (.NET Framework 3.5 SP1) ObjectSet (.NET Framework 4) ObjectQuery using (ChinookEntities context = new ChinookEntities()) { ObjectSet albums = context.Albums;var query = from album in albums where album.Artist.Name == "Deep Purple" select new { Title = album.Title, Name = album.Artist.Name }; Console.WriteLine("Album title: "); foreach (var q in query) {Console.WriteLine(q.Name + ": " + q.Title); } VSUG DAY 2010.05.09 21. LINQ to Entities (LINQ) Entity SQL SQL. SQL Entity Data Model LINQ EntitySQL VSUG DAY 2010.05.09 22. Entity SQLEntity Framework SQL Entity SQL SQL SELECT VALUE p.Name FROM AdventureWorksEntities.Product as p VSUG DAY 2010.05.09 23. ObjectQuery Entity SQL Distinct(), Except(), GroupBy(), Intersect(), OfType(), OrderBy(), Select(), SelectValue(), Skip(), Top(), Union(), UnionAll(), Where() VSUG DAY 2010.05.09 24. LINQ to Entities VSUG DAY 2010.05.09 25. LINQ to Entities using (AdventureWorksEntities AWEntities = new AdventureWorksEntities()) { var query = AWEntities.Products.Select(product => new{ProductId = product.ProductID,ProductName = product.Name});Console.WriteLine("Product Info:"); foreach (var productInfo in query) {Console.WriteLine("Product Id: {0} Product name: {1} ",productInfo.ProductId, productInfo.ProductName); } } VSUG DAY 2010.05.09 26. LINQ to Entities using (AdventureWorksEntities AWEntities = new AdventureWorksEntities()) { ObjectSet products = AWEntities.Products; IQueryable productsQuery = from product in products select product;Console.WriteLine("Product Names:"); foreach (var prod in productsQuery) {Console.WriteLine(prod.Name); } }VSUG DAY 2010.05.09 27. LINQ to Entities ObjectSet orders = AWEntities.SalesOrderHeaders; var onlineOrders =from order in orderswhere order.OnlineOrderFlag == trueselect new{ SalesOrderID = order.SalesOrderID, OrderDate = order.OrderDate, SalesOrderNumber = order.SalesOrderNumber};VSUG DAY 2010.05.09 28. LINQ to Entities ObjectSet products = AWEntities.Products; var query = from product in products group product by product.Style into g select new {Style = g.Key,AverageListPrice = g.Average(product => product.ListPrice) }; foreach (var product in query){ Console.WriteLine("Product style: {0} Average list price: {1}", product.Style, product.AverageListPrice);} VSUG DAY 2010.05.09 29. LINQ to Entities var query = (from album in albumswhere album.Artist.Name == "Deep Purple"orderby album.Titleselect new { Title = album.Title, Name = album.Artist.Name }).Take(3);VSUG DAY 2010.05.09 30. LINQ to EntitiesGroupJoin() var query = from contact in contacts join order in orders on contact.ContactID equals order.Contact.ContactID into contactGroup select new {ContactID = contact.ContactID,OrderCount = contactGroup.Count(),Orders = contactGroup.Select(order => order) }; VSUG DAY 2010.05.09 31. LINQ to Entitiesvar query = (from contact in contactsgroup contact by contact.LastName.Substring(0, 1) into contactGroupselect new { FirstLetter = contactGroup.Key,ContactGroup = contactGroup }). OrderBy(letter => letter.FirstLetter); foreach (var contact in query){ Console.WriteLine("Last names that start with the letter '{0}':",contact.FirstLetter); foreach (var name in contact.ContactGroup) {Console.WriteLine(name.LastName); }} VSUG DAY 2010.05.09 32. Load LazyLoadingEnabledtrue ObjectQuery Include(String) VSUG DAY 2010.05.09 33. Contact customer = context.Contacts .Where("it.ContactID = @customerId", new ObjectParameter("customerId", customerId)).First();if (!customer.SalesOrderHeaders.IsLoaded) { customer.SalesOrderHeaders.Load(); }foreach (SalesOrderHeader order in customer.SalesOrderHeaders) {if (!order.SalesOrderDetails.IsLoaded){order.SalesOrderDetails.Load();}VSUG DAY 2010.05.09 34. Entity Framework LazyLoadingEnabled truecontext.ContextOptions.LazyLoadingEnabled = true; (EntityReference ) (EntityCollection ) Detached() Detached() VSUG DAY 2010.05.09 35. var contacts = (from contact in context.Contacts .Include("SalesOrderHeaders.SalesOrderDetails") select contact).FirstOrDefault(); try {foreach (SalesOrderHeader order in contacts.SalesOrderHeaders){ Console.WriteLine(String.Format("PO Number: {0}",order.PurchaseOrderNumber)); Console.WriteLine(String.Format("Order Date: {0}",order.OrderDate.ToString())); Console.WriteLine("Order items:"); foreach (SalesOrderDetail item in order.SalesOrderDetails) {Console.WriteLine(String.Format("Product: {0} " + "Quantity: {1}", item.ProductID.ToString(), item.OrderQty.ToString())); }}VSUG DAY 2010.05.09 36. VSUG DAY 2010.05.09 37. using (ChinookEntities context = new ChinookEntities()) { ObjectSet artists = context.Artists;//ArtistIdIdentity0 Artist artist = Artist.CreateArtist(0);artist.Name = "Atsushi Fukui"; artists.AddObject(artist); context.SaveChanges();Console.WriteLine("Added Artist id {0} name {1}", artist.ArtistId, artist.Name);VSUG DAY 2010.05.09 38. using (ChinookEntities context = new ChinookEntities()) { ObjectSet artists = context.Artists; Artist artist = artists.Where("[email protected]", new ObjectParameter("name", "Atsushi Fukui")).First(); if (artist != null) { artists.DeleteObject(artist); context.SaveChanges(); } } VSUG DAY 2010.05.09 39. object entity = null; IEnumerable> keyValues =new KeyValuePair[]{new KeyValuePair("ArtistId", 279)}; EntityKey key = new EntityKey("ChinookEntities.Artists", keyValues); if (context.TryGetObjectByKey(key, out entity)) { Artist artist = (Artist)entity; artist.Name = "Hideharu Moriya"; context.SaveChanges(); } Artist a = context.Artists.Where(o => o.ArtistId == 279).First(); if (a != null) { Console.WriteLine(artist id {0}, name {1}, a.ArtistId, a.Name); }VSUG DAY 2010.05.09 40. ID ObjectStateEntry EntityKey EntityState ObjectStateEntry ObjectStateManager ObjectStateManager 1 VSUG DAY 2010.05.09 41. Added SaveChanges() Unchanged Deleted Detached Detached Detach(Object) NoTracking MergeOption Modified SaveChanges POCO DetectChanges Modified Unchanged Unchanged SaveChanges VSUG DAY 2010.05.09 42. Entity Framework POCO ObjectStateEntry Added Detached ObjectStateEntry ObjectStateEntry POCO ObjectStateEntry VSUG DAY 2010.05.09 43. ID 1 ID MergeOption var orders = Customer.Orders.Execute(MergeOption.PreserveChanges); VSUG DAY 2010.05.09 44. AppendOnly AppendOnly() OverwriteChanges PreserveChanges.NET Framework 3.5 SP1 UnchangedUnchanged.NET Framework 4 NoTracking DetachedObjectStateManager Entity Framework POCO VSUG DAY 2010.05.09 45. ConcurrencyMode=Fixed Entity Framework SQL Server VSUG DAY 2010.05.09 46. VSUG DAY 2010.05.09 47. VSUG DAY 2010.05.09 48. Entity Data Model: CSDLVSUG DAY 2010.05.09 49. Table-Per-Type BaseType ID IDID Table-Per-Hierarchy BaseType Is NullIs Not NullVSUG DAY 2010.05.09 50. SQL-- Creating table 'Parties' CREATE TABLE [dbo].[Parties] ( [Id] int IDENTITY(1,1) NOT NULL, [Name] nvarchar(max) NOT NULL ); GO-- Creating table 'Parties_Organization' CREATE TABLE [dbo].[Parties_Organization] ( [Location] nvarchar(max) NOT NULL, [Id] int NOT NULL ); GO-- Creating table 'Parties_Person' CREATE TABLE [dbo].[Parties_Person] ( [Age] int NOT NULL, [Id] int NOT NULL ); GOVSUG DAY 2010.05.09 51. VSUG DAY 2010.05.09 52. VSUG DAY 2010.05.09 53. N ASP.NETWCFWeb Silverlight VSUG DAY 2010.05.09 54. EntityKey WCF XML .NET Framework 4 Detached() VSUG DAY 2010.05.09 55. Entity Framework NoTracking() ASP.NET Web VSUG DAY 2010.05.09 56. Unchanged VSUG DAY 2010.05.09 57. ObjectSetAddObject() ObjectContext Added ObjectContextAddObject(S tring, Object) ObjectSetAttach() ObjectContext Unchanged Unchanged ObjectContextAttach(IEntit Entity Framework yWithKey) Entity Framework AttachTo(String, Object) AddObject VSUG DAY 2010.05.09 58. private static void ApplyItemUpdates(SalesOrderDetail originalItem, SalesOrderDetail updatedItem) {using (AdventureWorksEntities advWorksContext = new AdventureWorksEntities()){try{ //Item advWorksContext.Attach(originalItem);//ApplyCurrentValues advWorksContext.ApplyCurrentValues(SalesOrderDetails, updatedItem); advWorksContext.SaveChanges(); } catch (InvalidOperationException ex) { Console.WriteLine(ex.ToString()); } } }VSUG DAY 2010.05.09 59. VSUG DAY 2010.05.09 60. //static void UpdateDepartmentAndCourses(int departmentID, int courseID) { using (var service = new Service1Client()) {List departments = service.GetDepartments();Department department = departments.Single(d => d.DepartmentID == departmentID);department.Budget = department.Budget - 1000.00m;Course existingCourse = department.Courses.Single(c => c.CourseID == courseID); existingCourse.Credits = 3;service.UpdateDepartment(department); } }VSUG DAY 2010.05.09 61. //public void UpdateDepartment(Department updated) {using (SchoolEntities context = new SchoolEntities()) {try{context.Departments.ApplyChanges(updated);context.SaveChanges(); } catch (UpdateException) {throw;} } } VSUG DAY 2010.05.09 62. ADO.NET Entity FrameworkEDM N WCF ObjectContext IObjectSetVSUG DAY 2010.05.09 63. Entity Framework n http://msdn.microsoft.com/ja-jp/magazine/dd882522.aspx n http://msdn.microsoft.com/ja-jp/magazine/ee321569.aspx : http://msdn.microsoft.com/ja-jp/library/cc716679(v=VS.100).aspx Walkthrough: Serialize Self-Tracking Entities (Entity Framework) http://msdn.microsoft.com/en-us/library/ee789839(v=VS.100).aspx Entity Framework FAQ http://blogs.msdn.com/dsimmons/pages/entity-framework-faq.aspxVSUG DAY 2010.05.09 64. VSUG DAY 2010.05.09 65. AppendixVSUG DAY 2010.05.09 66. EdmGen.exe C#"%windir%Microsoft.NETFrameworkv4.0.30319edmgen.exe" /mode:EntityClassGeneration /incsdl:.School.csdl /outobjectlayer:.School.Objects.cs /language:CSharp VB"%windir%Microsoft.NETFrameworkv4.0.30319edmgen.exe" /mode:EntityClassGeneration /incsdl:.School.csdl /outobjectlayer:.School.Objects.vb /language:VBVSUG DAY 2010.05.09 67. : EntityContainer VSUG DAY 2010.05.09 68. : EntityType VSUG DAY 2010.05.09 69. : Association VSUG DAY 2010.05.09 70. : EntityContainer VSUG DAY 2010.05.09 71. : EntityType VSUG DAY 2010.05.09 72. : Association VSUG DAY 2010.05.09 73. : EntityMapping VSUG DAY 2010.05.09 74. ObjectContext SaveChanges()Refresh(RefreshMode, IEnumerable) ObjectQuery FirstOrDefault(IEnumerable) First(IEnumerable) EntityCollection Load(MergeOption) EntityReference Load(MergeOption) (LINQ) ObjectQuery (Where(String, ObjectParameter[])OrderBy(String, ObjectParameter[])Select(String,ObjectParameter[]) ) ObjectResult VSUG DAY 2010.05.09 75. using (AdventureWorksEntities advWorksContext = new AdventureWorksEntities()) { try {//advWorksContext.Connection.Open();// SalesOrderHeader order = advWorksContext.SalesOrderHeaders.Where( "it.SalesOrderID = @orderId", new ObjectParameter("orderId", orderId)) .Execute(MergeOption.AppendOnly).First(); order.Status = 1;// if (0 < advWorksContext.SaveChanges()){Console.WriteLine("Changes saved.");} } catch (InvalidOperationException ex) {Console.WriteLine(ex.ToString()); } // Dispose } VSUG DAY 2010.05.09