- Artikel
Notiz
Diese Funktion wurde in EF Core 7 hinzugefügt.
WährendReverse EngineeringZiel von Entity Framework Core ist es, guten, universellen Code zu entwickeln, der in einer Vielzahl von App-Typen und -Anwendungen verwendet werden kannGemeinsame Codierungskonventionenfür ein einheitliches Erscheinungsbild und ein vertrautes Gefühl. Manchmal sind jedoch spezialisierterer Code und alternative Codierungsstile wünschenswert. In diesem Artikel wird gezeigt, wie Sie den Gerüstcode anpassenT4-Textvorlagen.
Voraussetzungen
In diesem Artikel wird davon ausgegangen, dass Sie damit vertraut sindReverse Engineering in EF Core. Wenn nicht, lesen Sie bitte diesen Artikel, bevor Sie fortfahren.
Hinzufügen der Standardvorlagen
Der erste Schritt zum Anpassen des Gerüstcodes besteht darin, die Standardvorlagen zu Ihrem Projekt hinzuzufügen. Die Standardvorlagen werden intern von EF Core beim Reverse Engineering verwendet. Sie bieten Ihnen einen Ausgangspunkt für die Anpassung des Gerüstcodes.
Beginnen Sie mit der Installation des EF Core-Vorlagenpakets fürdotnet neu
:
dotnet neu installieren Microsoft.EntityFrameworkCore.Templates
Jetzt können Sie die Standardvorlagen zu Ihrem Projekt hinzufügen. Führen Sie dazu den folgenden Befehl in Ihrem Projektverzeichnis aus.
Dotnet neue EF-Vorlagen
Dieser Befehl fügt Ihrem Projekt die folgenden Dateien hinzu.
- CodeTemplates/
- EFCore/
- DbContext.t4
- EntityType.t4
- EFCore/
DerDbContext.t4
Die Vorlage wird verwendet, um eine DbContext-Klasse für die Datenbank zu erstellen, und dieEntityType.t4
Die Vorlage wird zum Gerüstbau von Entitätstypklassen für jede Tabelle und Ansicht in der Datenbank verwendet.
Spitze
Die Erweiterung .t4 wird (anstelle von .tt) verwendet, um zu verhindern, dass Visual Studio die Vorlagen transformiert. Die Vorlagen werden stattdessen von EF Core transformiert.
Einführung in T4
Lasst uns das öffnenDbContext.t4
Vorlage und überprüfen Sie deren Inhalt. Diese Datei ist eineT4-Textvorlage. T4 ist eine Sprache zum Generieren von Text mithilfe von .NET. Der folgende Code dient nur zur Veranschaulichung; es stellt nicht den vollständigen Inhalt der Datei dar.
Wichtig
T4-Textvorlagen – insbesondere solche, die Code generieren – können ohne Syntaxhervorhebung schwer zu lesen sein. Suchen Sie bei Bedarf nach einer Erweiterung Ihres Code-Editors, die die Hervorhebung der T4-Syntax ermöglicht.
<#@ template hostSpecific="true" #><#@ Assemblyname="Microsoft.EntityFrameworkCore.Design" #><#@ Parametername="NamespaceHint" type="System.String" #><#@ import namespace= "Microsoft.EntityFrameworkCore" #><# if (!string.IsNullOrEmpty(NamespaceHint)) {#>namespace <#= NamespaceHint #>;
Die ersten paar Zeilen, die mit beginnen<#@
werden Direktiven genannt. Sie wirken sich darauf aus, wie die Vorlage transformiert wird. In der folgenden Tabelle werden die einzelnen Arten der verwendeten Direktiven kurz beschrieben.
Richtlinie | Beschreibung |
---|---|
Vorlage | Gibt hostSpecific="true" an, was die Verwendung von ermöglichtGastgeber Eigenschaft innerhalb der Vorlage, um auf EF Core-Dienste zuzugreifen. |
Montage | Fügt Assemblyverweise hinzu, die zum Kompilieren der Vorlage erforderlich sind. |
Parameter | Deklariert Parameter, die von EF Core beim Transformieren der Vorlage übergeben werden. |
importieren | Bringt wie C# durch die Verwendung von Direktiven Namespaces in den Gültigkeitsbereich des Vorlagencodes. |
Nach den Anweisungen folgt der nächste Abschnitt vonDbContext.t4
wird als Steuerblock bezeichnet. Ein Standardkontrollblock beginnt mit<#
und endet mit#>
. Der darin enthaltene Code wird beim Transformieren der Vorlage ausgeführt. Eine Liste der in Steuerblöcken verfügbaren Eigenschaften und Methoden finden Sie unterTexttransformationKlasse.
Alles außerhalb eines Kontrollblocks wird direkt in die Vorlagenausgabe kopiert.
Ein Ausdruckskontrollblock beginnt mit<#=
. Der darin enthaltene Code wird ausgewertet und das Ergebnis wird der Vorlagenausgabe hinzugefügt. Diese ähneln C#-interpolierten Zeichenfolgenargumenten.
Eine detailliertere und vollständigere Erklärung der T4-Syntax finden Sie unterSchreiben einer T4-Textvorlage.
Passen Sie die Entitätstypen an
Lassen Sie uns durchgehen, wie es ist, eine Vorlage anzupassen. Standardmäßig generiert EF Core den folgenden Code für Sammlungsnavigationseigenschaften.
public virtual ICollection Albums { get; } = new List();
BenutzenListe
ist für die meisten Anwendungen eine gute Standardeinstellung. Wenn Sie jedoch ein XAML-basiertes Framework wie WPF, WinUI oder .NET MAUI verwenden, möchten Sie es häufig verwendenObservableCollection
Stattdessen wird die Datenbindung aktiviert.
Öffne dasEntityType.t4
Vorlage und finden Sie heraus, wo sie generiert wirdListe
. Es sieht aus wie das:
if (navigation.IsCollection) {#> public virtual ICollection<<#= targetType #>> <#= navigation.Name #> { get; } = new List<<#= targetType #>>();<# }
Ersetzen Sie List durch ObservableCollection.
öffentliche virtuelle ICollection<<#= targetType #>> <#= navigation.Name #> { get; } = new ObservableCollection<<#= targetType #>>();
Wir müssen auch a hinzufügenverwenden
Direktive für den Gerüstcode. Die Verwendungszwecke werden in einer Liste oben in der Vorlage angegeben. HinzufügenSystem.Collections.ObjectModel
zur Liste.
var usings = new List{ "System", "System.Collections.Generic", "System.Collections.ObjectModel"};
Testen Sie die Änderungen mithilfe der Reverse-Engineering-Befehle. Die Vorlagen in Ihrem Projekt werden von den Befehlen automatisch verwendet.
- .NET Core-CLI
- Visual Studio
dotnet ef dbcontext scaffold „Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=Chinook“ Microsoft.EntityFrameworkCore.SqlServer
Wenn Sie den Befehl zuvor ausgeführt haben, fügen Sie den hinzu--Gewalt
Option zum Überschreiben der vorhandenen Dateien.
Wenn Sie alles richtig gemacht haben, sollten die Navigationseigenschaften der Sammlung jetzt verwendet werdenObservableCollection
.
public virtual ICollection Albums { get; } = new ObservableCollection();
Aktualisieren von Vorlagen
Wenn Sie die Standardvorlagen zu Ihrem Projekt hinzufügen, wird eine Kopie davon basierend auf dieser Version von EF Core erstellt. Da Fehler behoben und Funktionen in nachfolgenden Versionen von EF Core hinzugefügt werden, sind Ihre Vorlagen möglicherweise veraltet. Sie sollten die an den EF Core-Vorlagen vorgenommenen Änderungen überprüfen und sie in Ihre benutzerdefinierten Vorlagen einbinden.
Eine Möglichkeit, die an den EF Core-Vorlagen vorgenommenen Änderungen zu überprüfen, besteht darin, sie mit Git zwischen den Versionen zu vergleichen. Der folgende Befehl klont das EF Core-Repository und generiert einen Unterschied dieser Dateien zwischen den Versionen 7.0.0 und 8.0.0.
git clone --no-checkout https://github.com/dotnet/efcore.gitcd efcoregit diff v7.0.0 v8.0.0 -- src/EFCore.Design/Scaffolding/Internal/CSharpDbContextGenerator.tt src/EFCore.Design/Scaffolding /Internal/CSharpEntityTypeGenerator.tt
Eine andere Möglichkeit, die Änderungen zu überprüfen, besteht darin, die beiden Versionen von herunterzuladenMicrosoft.EntityFrameworkCore.TemplatesExtrahieren Sie aus NuGet deren Inhalte (Sie können die Dateierweiterungen in „.zip“ ändern) und vergleichen Sie diese Dateien.
Bevor Sie die Standardvorlagen zu einem neuen Projekt hinzufügen, denken Sie daran, auf das neueste EF Core-Vorlagenpaket zu aktualisieren.
Dotnet neues Update
Erweiterte Nutzung
Ignorieren des Eingabemodells
DerModell
UndEntitätstyp
Parameter stellen eine mögliche Möglichkeit der Zuordnung zur Datenbank dar. Sie können Teile des Modells ignorieren oder ändern. Beispielsweise sind die von uns bereitgestellten Navigationsnamen möglicherweise nicht ideal und Sie können sie beim Gerüstbau des Codes durch Ihre eigenen ersetzen. Andere Dinge wie Einschränkungsnamen und Indexfilter werden nur von Migrations verwendet und können im Modell getrost weggelassen werden, wenn Sie nicht beabsichtigen, Migrations mit dem Gerüstcode zu verwenden. Ebenso möchten Sie möglicherweise Sequenzen oder Standardeinschränkungen weglassen, wenn diese nicht von Ihrer App verwendet werden.
Wenn Sie erweiterte Änderungen wie diese vornehmen, stellen Sie einfach sicher, dass das resultierende Modell mit der Datenbank kompatibel bleibt. Überprüfen des von generierten SQLdbContext.Database.GenerateCreateScript()
ist eine gute Möglichkeit, dies zu bestätigen.
Entitätskonfigurationsklassen
Bei großen Modellen kann die OnModelCreating-Methode der DbContext-Klasse unüberschaubar groß werden. Eine Möglichkeit, dem entgegenzuwirken, ist die VerwendungIEntityTypeConfiguration
Klassen. SehenErstellen und Konfigurieren eines ModellsWeitere Informationen zu diesen Kursen finden Sie hier.
Zum Gerüstbau dieser Klassen können Sie eine dritte Vorlage namens verwendenEntityTypeConfiguration.t4
. WieEntityType.t4
Vorlage, sie wird für jeden Entitätstyp im Modell verwendet und verwendet dieEntitätstyp
Vorlagenparameter.
Gerüst für andere Dateitypen
Der Hauptzweck des Reverse Engineering in EF Core besteht darin, ein Gerüst für einen DbContext und Entitätstypen zu erstellen. Allerdings gibt es in den Tools nichts, was ein tatsächliches Gerüstcode erfordern würde. Beispielsweise könnten Sie stattdessen ein Entity-Relationship-Diagramm mithilfe von Gerüst erstellenMeerjungfrau.
<#@ Output Extension=".md" #><#@ Assemblyname="Microsoft.EntityFrameworkCore" #><#@ Assemblyname="Microsoft.EntityFrameworkCore.Relational" #><#@ Assemblyname="Microsoft.EntityFrameworkCore .Design" #><#@ Parametername="Model" type="Microsoft.EntityFrameworkCore.Metadata.IModel" #><#@ Parametername="Options" type="Microsoft.EntityFrameworkCore.Scaffolding.ModelCodeGenerationOptions" #>< #@ import namespace="System.Linq" #><#@ import namespace="Microsoft.EntityFrameworkCore" #># <#= Options.ContextName #>```mermaiderDiagram<# foreach (var entityType in Model.GetEntityTypes() .Where(e => !e.IsSimpleManyToManyJoinEntityType())) {#> <#=EntityType.Name #> { > <#= ForeignKey.IsUnique ? „|“ : "}" #>o--<#= ForeignKey.IsRequired ? „|“ : "o" #>| <#= ForeignKey.PrincipalEntityType.Name #> : <#= ForeignKey.GetConstraintName() #><# } foreach (var SkipNavigation in EntityType.GetSkipNavigations().Where(n => n.IsLeftNavigation())) {#> <#= entityType.Name #> }o--o{ <#= SkipNavigation.TargetEntityType.Name #> : <#= SkipNavigation.JoinEntityType.Name #><# } }#>```
FAQs
What is EF Core reverse engineering? ›
Reverse engineering is the process of scaffolding entity type classes and a DbContext class based on a database schema. It can be performed using the Scaffold-DbContext command of the EF Core Package Manager Console (PMC) tools or the dotnet ef dbcontext scaffold command of the . NET Command-line Interface (CLI) tools.
Is EF core any good? ›Conclusion. EF should be considered a great ORM framework which allows faster development, easier and quicker operations to the DB, as long as you are careful and know how it works in order to avoid certain mistakes and create performance problems.
What is the newest EF core? ›EF Core 7.0 (EF7) was released in November 2022.
Is EF core an ORM? ›EF Core is an object-relational mapper (ORM). Object-relational mapping is a technique that enables developers to work with data in an object-oriented way by performing the work required to map between objects defined in an application's programming language and data stored in relational data sources.
Why not to use EF Core? ›One of the biggest reasons not to use Entity Framework Core is that your application needs the fastest possible data access. Some applications do a lot of heavy data operations with very high-performance demands, but usually business applications don't have that high of a performance demand.
Should I use EF core or Dapper? ›Dapper is generally faster than EF Core because it uses raw SQL queries and has less overhead. However, EF Core provides caching and other performance optimizations that can sometimes make it faster. Dapper is simpler than EF Core because it uses raw SQL queries and has fewer features.
Is EF core production ready? ›Entity Framework Core 5 RC1 Is Feature Complete, Ready for Production. The first release candidate for Entity Framework 5 -- Microsoft's object-database mapper for . NET -- has shipped with a go live license, ready for production.
What is the difference between EF core and EF? ›Entity Framework Core is the new version of Entity Framework after EF 6.x. It is open-source, lightweight, extensible and a cross-platform version of Entity Framework data access technology. Entity Framework is an Object/Relational Mapping (O/RM) framework.
Is Canon phasing out EF lenses? ›The rapid discontinuation of EF and EF-S mount lenses appears to reflect the obvious shift of Canon from DSLR production to mirrorless camera production. Indeed, in January 2022 Canon's CEO and Chairman, Fujio Mitarai, admitted that the EOS-1D X Mark III would be Canon's last flagship DSLR camera.
Is Canon discontinuing EF lenses? ›There's a reason for this, and that is: Canon has quietly discontinued 30 DSLR lenses – including Canon EF / EF-S DSLR lenses.
Should I use EF6 or EF Core? ›
Keep using EF6 if the data access code is stable and not likely to evolve or need new features. Port to EF Core if the data access code is evolving or if the app needs new features only available in EF Core. Porting to EF Core is also often done for performance.
Which features are not supported in EF Core? ›Although both of these releases provides similar features, EF Core does not have following features: Spatial Type. Complex/value types. EDMX Model format.
What is the difference between .NET core and EF core? ›Entity Framework Core is an object-database mapper (and a successor to Entity Framework). . NET Core is a cross-platform software framework developed by Microsoft (and a successor to . NET Framework).
What does EF core stand for? ›Entity Framework (EF) Core is a lightweight, extensible, open source and cross-platform version of the popular Entity Framework data access technology.
What is the advantage of EF core? ›- Entity Framework helps to reduce development time and development cost.
- It provides auto-generated code and allows developers to visually design models and mapping of databases.
- It allows easy mapping of Business Objects.
- It helps to perform fast CRUD operations in .
Lazy loading means that the related data is transparently loaded from the database when the navigation property is accessed.
Is EF Core 5.0 many to many? ›EF Core 5.0 recognizes this as a many-to-many relationship by convention, and automatically creates a PostTag join table in the database. Data can be queried and updated without explicitly referencing the join table, considerably simplifying code. The join table can still be customized and queried explicitly if needed.
How does EF support inheritance? ›By default, EF maps the inheritance using the table-per-hierarchy (TPH) pattern. TPH uses a single table to store the data for all types in the hierarchy, and a discriminator column is used to identify which type each row represents.
What is advantage and disadvantage of Entity Framework? ›Easy to map business objects (with drag & drop tables on environment). It keeps a good performance when you work with a small / middle domain model. Disadvantages: You have to think in a non-traditional way of handling data , not available for every database.
What is better than Dapper? ›EF Core generates SQL statements automatically, which can be slower than manually written SQL in some cases. However, EF Core's performance is generally good enough for most applications, and it is easier to use than Dapper for simple queries.
Can you use EF core with .NET framework? ›
You can use EF Core in APIs and applications that require the full . NET Framework, as well as those that target only the cross-platform .
What is the difference between LINQ and EF core? ›LINQ allows you to use C# (or your . NET language of choice) to write strongly typed queries. It uses your derived context and entity classes to reference database objects. EF Core passes a representation of the LINQ query to the database provider.
What is the best way to seed data in EF core? ›One way to seed data in EF Core is by using the DbContext. Database. EnsureCreated() method in your DbContext class. This method will create the database and apply any seed data that you have defined in your DbContext class.
Is EF core faster than EF6? ›Note that for a single row, EF Core is slower than EF6 unless using context pooling; this could be the cost of setting up all the scoped services for each instance (which isn't done when context pooling is on). For multiple rows, EF Core batches and EF6 doesn't, so EF Core quickly becomes much faster.
Which platform supports EF Core? ›EF Core's support on . NET for Windows, Linux, and macOS is covered by automated testing and many applications are known to be using it successfully, other platforms that leverage trimming and ahead-of-time (AoT) compilation like iOS, Wasm, and Unity have some limitations that we are working to address.
What is the difference between EF5 and EF6? ›EF5 is built into the core of . NET 4.5, whereas EF6 has been shifted out, and is open source. This means that you must add the new EF6 assemblies to all of the relevant projects in the solution, in particular the entry project. This means that you must remove assembly System.
How do I migrate EF to EF core? ›- Install EF Core NuGet packages. ...
- Swap namespaces. ...
- Context configuration (connection etc.) ...
- Update your code. ...
- Existing migrations. ...
- Test the port.
In Entity Framework Core (also called EF Core), a Db context is an object that coordinates queries, updates, and deletes against your database. It takes care of performing CRUD operations against your database. The DbContext, the central object in Entity Framework Core, is a gateway to your database.
What is EF core used for? ›EF Core can serve as an object-relational mapper (O/RM), which: Enables .NET developers to work with a database using .NET objects. Eliminates the need for most of the data-access code that typically needs to be written.
What is the reverse engineer function in EF Core Power Tools? ›What is the Reverse Engineer option in EF Core Power Tools up to? Reverse Engineer has the role of the Entity Data Model, which transforms the tables in the existing database to C# classes with a DbContext class.
What is EF in software engineering? ›
Entity Framework (EF) is an open source object–relational mapping (ORM) framework for ADO.NET. It was originally shipped as an integral part of . NET Framework, however starting with Entity Framework version 6.0 it has been delivered separately from the . NET Framework.
What is EF programming? ›Entity Framework (EF) is an object-relational mapper for . NET developers that allows them to work with relational data using domain-specific objects. It eliminates the majority of the data-access code that developers must routinely write.
What is difference between EF and EF core? ›Keep using EF6 if the data access code is stable and not likely to evolve or need new features. Port to EF Core if the data access code is evolving or if the app needs new features only available in EF Core. Porting to EF Core is also often done for performance.
What is the difference between reverse engineering and reengineering tools? ›Re-engineering is usually used to update the functionality of a product whereas reverse engineering is mostly used to peep into the working of the product and what goes into the making.
How does EF core change tracking work? ›EF Core tracks changes at the property level. For example, if only a single property value is modified, then a database update will change only that value. However, properties can only be marked as modified when the entity itself is in the Modified state.
What are the benefits of using EF? ›The Entity Framework enables developers to work with data in the form of domain-specific objects and properties, such as customers and customer addresses, without having to concern themselves with the underlying database tables and columns where this data is stored.
How do you optimize EF? ›- Use indexes properly.
- Project only properties you need.
- Limit the resultset size.
- Efficient pagination.
- Avoid cartesian explosion when loading related entities.
- Load related entities eagerly when possible.
- Buffering and streaming.
- Tracking, no-tracking and identity resolution.
Dapper is generally faster than EF Core because it uses raw SQL queries and has less overhead. However, EF Core provides caching and other performance optimizations that can sometimes make it faster. Dapper is simpler than EF Core because it uses raw SQL queries and has fewer features.
What is EF core equivalent in Python? ›The Python equivalent of EF is a clever and mature library called SQLAlchemy. With SQLAlchemy, you will find code that is very similar to EF code. You define classes and use them to model the data and you use them as the basis for queries. You can find SQLAlchemy at https://www.sqlalchemy.org/.
What databases does EF core work with? ›- Microsoft SQL Server.
- Microsoft SQL Server Compact Edition.
- SQLite.
- MySQL.
- PostgreSQL.
- In-memory databases and more.
What are the EF core commands? ›
Option | Short | Description |
---|---|---|
--output <FILE> | -o | The path of executable file to create. |
--force | -f | Overwrite existing files. |
--self-contained | Also bundle the .NET runtime so it doesn't need to be installed on the machine. | |
--target-runtime <RUNTIME_IDENTIFIER> | -r | The target runtime to bundle for. |