Kurse:Entity Framework Core: Unterschied zwischen den Versionen
Zur Navigation springen
Zur Suche springen
Die Seite wurde neu angelegt: „= Entity Framework Core (EF Core) Spickzettel = == Was ist EF Core? == * EF Core ist ein moderner, leichter und erweiterbarer Object-Relational Mapper (ORM) für .NET. * Erlaubt die Arbeit mit Datenbankdaten als .NET-Objekte (Entities), anstatt mit SQL-Queries. == Grundkonzepte == * '''Entities''': C#-Klassen, die Datenbanktabellen repräsentieren. * '''DbContext''': Brücke zwischen Entities und Datenbank. * '''DbSet<TEntity>''': Sammlung einer Entitä…“ |
Keine Bearbeitungszusammenfassung |
||
| Zeile 1: | Zeile 1: | ||
= | == EF Core Cheatsheet (Deutsch) == | ||
== | === DbContext & DbSet === | ||
= | |||
<syntaxhighlight lang="csharp"> | <syntaxhighlight lang="csharp"> | ||
public class PersonsDbContext : DbContext | public class PersonsDbContext : DbContext | ||
{ | { | ||
public DbSet<Person> Persons { get; set; } | |||
public DbSet<Country> Countries { get; set; } | public DbSet<Country> Countries { get; set; } | ||
protected override void OnModelCreating(ModelBuilder modelBuilder) | protected override void OnModelCreating(ModelBuilder modelBuilder) | ||
{ | { | ||
| Zeile 38: | Zeile 16: | ||
</syntaxhighlight> | </syntaxhighlight> | ||
== | === Verbindungskette (appsettings.json) === | ||
<syntaxhighlight lang="json"> | |||
{ | |||
"ConnectionStrings": { | |||
"DefaultConnection": "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=PersonsDatabase;Integrated Security=True" | |||
} | |||
} | |||
</syntaxhighlight> | |||
== | === DI Registrierung (Program.cs) === | ||
<syntaxhighlight lang="csharp"> | <syntaxhighlight lang="csharp"> | ||
builder.Services.AddDbContext<PersonsDbContext>(options => | builder.Services.AddDbContext<PersonsDbContext>(options => | ||
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"))); | options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"))); | ||
</syntaxhighlight> | </syntaxhighlight> | ||
=== LINQ-Abfrage mit Navigation === | |||
<syntaxhighlight lang=" | <syntaxhighlight lang="csharp"> | ||
var peopleFromUSA = _dbContext.Persons | |||
.Include(p => p.Country) | |||
.Where(p => p.Country.CountryName == "USA") | |||
.ToList(); | |||
</syntaxhighlight> | |||
=== Seed Data mit JSON-Dateien === | |||
<syntaxhighlight lang="csharp"> | |||
var countries = JsonSerializer.Deserialize<List<Country>>(File.ReadAllText("countries.json")); | |||
modelBuilder.Entity<Country>().HasData(countries); | |||
</syntaxhighlight> | </syntaxhighlight> | ||
== | === Fluent API Beispiel === | ||
<syntaxhighlight lang="csharp"> | <syntaxhighlight lang="csharp"> | ||
modelBuilder.Entity<Person>() | |||
.Property(p => p.TIN) | |||
.HasColumnName("TaxID") | |||
.HasColumnType("varchar(8)") | |||
.HasDefaultValue("ABC12345"); | |||
</syntaxhighlight> | </syntaxhighlight> | ||
== | === Migrationen (Konsole) === | ||
<syntaxhighlight lang="bash"> | <syntaxhighlight lang="bash"> | ||
dotnet ef migrations add InitialCreate | dotnet ef migrations add InitialCreate | ||
dotnet ef database update | dotnet ef database update | ||
</syntaxhighlight> | </syntaxhighlight> | ||
== | === Stored Procedure (Aufruf) === | ||
<syntaxhighlight lang="csharp"> | <syntaxhighlight lang="csharp"> | ||
public List<Person> GetPersons() => | |||
Persons.FromSqlRaw("EXEC dbo.GetAllPersons").ToList(); | |||
</syntaxhighlight> | </syntaxhighlight> | ||
== | === Create (Controller POST) === | ||
<syntaxhighlight lang="csharp"> | <syntaxhighlight lang="csharp"> | ||
[HttpPost] | |||
public async Task<IActionResult> Create(PersonAddRequest request) | |||
{ | |||
if (ModelState.IsValid) | |||
{ | |||
await _personsService.AddPerson(request); | |||
return RedirectToAction("Index"); | |||
} | |||
ViewBag.Countries = await _countriesService.GetAllCountries(); | |||
return View(request); | |||
} | |||
. | |||
</syntaxhighlight> | </syntaxhighlight> | ||
== | === PDF mit Rotativa === | ||
<syntaxhighlight lang="csharp"> | <syntaxhighlight lang="csharp"> | ||
public async Task<IActionResult> PersonsPDF() | |||
var | { | ||
var persons = await _personsService.GetAllPersons(); | |||
return new ViewAsPdf("PersonsPDF", persons) | |||
{ | |||
PageOrientation = Orientation.Landscape, | |||
PageMargins = { Top = 20, Bottom = 20, Left = 20, Right = 20 } | |||
}; | |||
} | |||
</syntaxhighlight> | </syntaxhighlight> | ||
== | === CSV mit CsvHelper === | ||
<syntaxhighlight lang="csharp"> | <syntaxhighlight lang="csharp"> | ||
public async Task<MemoryStream> GetPersonsCSV() | |||
{ | { | ||
csv.WriteRecords( | var stream = new MemoryStream(); | ||
using var writer = new StreamWriter(stream, leaveOpen: true); | |||
using var csv = new CsvWriter(writer, CultureInfo.InvariantCulture); | |||
var persons = await _dbContext.Persons.Include(p => p.Country).ToListAsync(); | |||
csv.WriteRecords(persons); | |||
writer.Flush(); | |||
stream.Position = 0; | |||
return stream; | |||
} | } | ||
</syntaxhighlight> | </syntaxhighlight> | ||
== | === Beziehungskonfiguration (Fluent API) === | ||
<syntaxhighlight lang="csharp"> | |||
modelBuilder.Entity<Person>() | |||
.HasOne(p => p.Country) | |||
.WithMany(c => c.Persons) | |||
.HasForeignKey(p => p.CountryID); | |||
= | </syntaxhighlight> | ||
Aktuelle Version vom 29. Juni 2025, 21:46 Uhr
EF Core Cheatsheet (Deutsch)
DbContext & DbSet
public class PersonsDbContext : DbContext
{
public DbSet<Person> Persons { get; set; }
public DbSet<Country> Countries { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Country>().ToTable("Countries");
modelBuilder.Entity<Person>().ToTable("Persons");
}
}
Verbindungskette (appsettings.json)
{
"ConnectionStrings": {
"DefaultConnection": "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=PersonsDatabase;Integrated Security=True"
}
}
DI Registrierung (Program.cs)
builder.Services.AddDbContext<PersonsDbContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
LINQ-Abfrage mit Navigation
var peopleFromUSA = _dbContext.Persons
.Include(p => p.Country)
.Where(p => p.Country.CountryName == "USA")
.ToList();
Seed Data mit JSON-Dateien
var countries = JsonSerializer.Deserialize<List<Country>>(File.ReadAllText("countries.json"));
modelBuilder.Entity<Country>().HasData(countries);
Fluent API Beispiel
modelBuilder.Entity<Person>()
.Property(p => p.TIN)
.HasColumnName("TaxID")
.HasColumnType("varchar(8)")
.HasDefaultValue("ABC12345");
Migrationen (Konsole)
dotnet ef migrations add InitialCreate
dotnet ef database update
Stored Procedure (Aufruf)
public List<Person> GetPersons() =>
Persons.FromSqlRaw("EXEC dbo.GetAllPersons").ToList();
Create (Controller POST)
[HttpPost]
public async Task<IActionResult> Create(PersonAddRequest request)
{
if (ModelState.IsValid)
{
await _personsService.AddPerson(request);
return RedirectToAction("Index");
}
ViewBag.Countries = await _countriesService.GetAllCountries();
return View(request);
}
PDF mit Rotativa
public async Task<IActionResult> PersonsPDF()
{
var persons = await _personsService.GetAllPersons();
return new ViewAsPdf("PersonsPDF", persons)
{
PageOrientation = Orientation.Landscape,
PageMargins = { Top = 20, Bottom = 20, Left = 20, Right = 20 }
};
}
CSV mit CsvHelper
public async Task<MemoryStream> GetPersonsCSV()
{
var stream = new MemoryStream();
using var writer = new StreamWriter(stream, leaveOpen: true);
using var csv = new CsvWriter(writer, CultureInfo.InvariantCulture);
var persons = await _dbContext.Persons.Include(p => p.Country).ToListAsync();
csv.WriteRecords(persons);
writer.Flush();
stream.Position = 0;
return stream;
}
Beziehungskonfiguration (Fluent API)
modelBuilder.Entity<Person>()
.HasOne(p => p.Country)
.WithMany(c => c.Persons)
.HasForeignKey(p => p.CountryID);