1 / 20

Ado.NET Entity framework

Ado.NET Entity framework. object - relational mapping framework. Čo je entity framework. Je to objektovo – relačný mapovací framework Ďalšia novinka v .NET 3.5 Je to niečo podobné ako LINQ to SQL Je dostupný od .NET 3.5 so Service Pack 1

necia
Télécharger la présentation

Ado.NET Entity framework

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Ado.NET Entity framework object - relationalmappingframework

  2. Čo je entity framework • Je to objektovo – relačný mapovacíframework • Ďalšia novinka v .NET 3.5 • Je to niečo podobné ako LINQ to SQL • Je dostupný od .NET 3.5 so Service Pack 1 • Rozdiely medzi entity frameworkom a LINQ to SQL - EF obsahuje viac možností pre vzťahy a dedičnosť - možnosť pripojiť EF na viac druhov úložísk - LINQ je jednoduchší

  3. Entity FrameworkLayers • EF ponúka viac vrstiev k mapovaniu databázových tabuliek do objektov • Na kompletné mapovanie sa dá využiť itemtemplate vo VisualStudiu, alebo spraviť mapovanie manuálne, pričom tabuľky a vzťahy môžu mať inú štruktúru • Vrstvy ktoré musia byť definované - Logicallayer– definuje relačné data - Conceptual l.– definuje .NET triedy - Mappingl. – definuje mapovanie z .NET tried k tabuľkám a vzťahom

  4. Logical layer • Popisuještruktúru databázových tabuliek a vzťahy medzi nimi • Definujesapomocou SSDL (Strore Definition Schema Language) • ElementyEntityContainer, EntitySet, EntityType • VzťahysadefinujúpomocouelementovAssociationSet, End Role

  5. Conceptuallayer • Táto vrstva definuje triedy .NET • Vytvárame ju pomocou CSDL (ConceptualSchemaDefinitionLanguage) • Entitu definujeme v elemente EntityType, ktorý obsahuje elementy Key, Property, NavigationProperty • Pri Association sa používa atribútMultiplicity ( Napr. Multiplicity= “*”, Multiplicity= “1”)

  6. Mappinglayer • Zobrazovaciamapovaciavrstva, zobrazujedefiníciu typu entity v CSDL na SSDL pomocou jazyka MappingSpecificationLanguage • elementy Mapping, EntityTypeMapping, MappingFragment, ScalarProperty, AssociationSetMapping

  7. Entity Framework architecture

  8. Prístup k entitám • Pre načítanie dát potrebujeme triedu ObjectContext (BookEntities: ObjectContext) BooksEntitiesdata = new BooksEntities(); foreach (var book in data.Books) { Console.WriteLine(book.Title); }

  9. ObjectContext • Obsahuje vlastnosti(properties), ktoré vracajú objekty typu ObjectQuery (napr. Books, Authors) • Ďalej obsahuje metódy pre pridávanie položiek do entít • Uchováva zoznam načítaných objektoch entít. Ak dôjde k opätovnému dotazu na určitý objekt, načíta sa obsahu objektu • Uchováva informácie o stavu entít ( o pridaných, upravených, vymazaných objektoch) • Môže aktualizovať entity v obsahu objektu a zapísať zmeny do úložiska

  10. ObjectContext

  11. Relácie • Jedna tabuľka na hierarchiu

  12. Ukážka < EntityTypeMappingTypeName=”IsTypeOf(PaymentModel.Entities.Payment)” > < MappingFragmentStoreEntitySet=”Payments” > < ScalarProperty Name=”Id” ColumnName=”Id” / > < ScalarProperty Name=”Amount” ColumnName=”Amount” / > < ScalarProperty Name=”Name” ColumnName=”Name” / > < /MappingFragment > < /EntityTypeMapping > < EntityTypeMapping TypeName=”IsTypeOf(PaymentModel.Entities.CashPayment)” > < MappingFragmentStoreEntitySet=”Payments” > < ScalarProperty Name=”Id” ColumnName=”Id” / > < Condition ColumnName=”Type” Value=”CASH” / > < /MappingFragment > < /EntityTypeMapping > . . .

  13. Relácie • Jenda tabuľka na typ

  14. Relácie NorthwindEntities data = new NorthwindEntities(); foreach (Customer customer in data.Customers) { Console.WriteLine(“{0}”, customer.CompanyName); if (!customer.Orders.IsLoaded) customer.Orders.Load(); foreach(Order order in customer.Orders) { Console.WriteLine(“{0} {1:d}”, order.OrderID, order.OrderDate); } } Navrhovanie zložitejších dátových modelov: http://msdn.microsoft.com/en-us/library/bb738640.aspx

  15. Accessing and Changing Entity Data • LINQ to Entities -využitie Language-Integrated Query (LINQ) k dotazovaniu na entity • Entity SQL – podobné SQL • Query Builder Methods – dovoľuje vytvárať Entity SQL queries s použitím LINQovského štýlu, pomocou metód

  16. Entity SQL a Query Builder -> SQL SQL SELECT [Extent1].[Id] AS [Id], [Extent1].[Firstname] AS [Firstname], [Extent1].[Lastname] AS [Lastname], [Extent1].[Country] AS [Country], [Extent1].[Starts] AS [Starts], [Extent1].[Wins] AS [Wins] FROM [dbo].[Racers] AS [Extent1] WHERE [Extent1].[Country] = @Country string country = “Brazil”; Query builder ObjectQuery < Racer > racers = data.Racers.Where(“it.Country = @Country”, new ObjectParameter(“Country”, country)); EntitySQL SELECT VALUE it FROM ( [Racers] ) AS it WHERE it.Country = @Country

  17. Query builder • Where(), Distinct(), Except(), GroupBy(), Include(), OfType(), OrderBy(), Select(), Skip(), Top(), Intersect(), Union() … string country = “USA”; ObjectQuery < Racer > racers = data.Racers.Where(“it.Country = @Country”, new ObjectParameter(“Country”, country)) .OrderBy(“it.Wins DESC, it.Starts DESC”) .Top(“3”);

  18. LINQ to Entities Formula1Entities data = new Formula1Entities() varracers = from r in data.Racers where r.Wins > 40 orderby r.Wins descending select r; var query = from r in data.Racers from rr in r.RaceResults where rr.Position < = 3 & & rr.Position > = 1 & & r.Country == “Switzerland” group r by r.Id into g let podium = g.Count() orderby podium descending select new { Racer = g.FirstOrDefault(), Podiums = podium };

  19. Ukladanie zmien v entitách • Po pridaní, zmazaní alebo editovaní sa zmeny vykonajú len v ObjectContexte • Použitie SaveChanges() • Pomocou udalosti ObjectContextu SavingChanges() môžme zistiť kedy sa dáta ukladajú • Pri zápise môže dôjsť k výnimke, pretože dáta v úložisku mohli by medzičasom zmenené • Ošetrenie nestavením vlastnosti ConcurrencyMode na fixed alebo none, alebo použiť metódu Refresh()

  20. Ukážka try { changes = data.SaveChanges(); } catch (OptimisticConcurrencyException ex) { data.Refresh(RefreshMode.ClientWins, ex.StateEntries); changes = data.SaveChanges(); }

More Related