Windows Console App C# .Net 6 mit EntityFrameworkCore 6+ SQL Server Tabellen bearbeiten
Mit diesem C# .Net Code kann man mit einer Konsolen-Anwendung (Windows App ohne User-Interface) Daten auf einem angebundenen SQL-Server als Service Bearbeiten.
Wichtig ist dabei, dass mit der EntityFrameworkCore die Datenabfragen Typ-Sicher und Sicher gegen SQL Injection abgerufen werden können und mit LINQ alle praktischen Abfragen vereinfacht werden.
Program.cs
using Database; using Microsoft.EntityFrameworkCore;
namespace ConsApp_DB02 { internal class Program { static void Main(string[] args) { Console.WriteLine("Console With Entity Framework");
string connectionstring = @"Server=.\sqlexpress;Database=codedocu_de;Trusted_Connection=True;MultipleActiveResultSets=true;Encrypt=false"; var dbOptions = new DbContextOptionsBuilder<ApplicationDbContext>().UseSqlServer(connectionstring).Options;
using (var dbContext = new ApplicationDbContext(dbOptions)) { var articles = dbContext.tbl_Articles.ToList().Take(10); foreach (var article in articles) { Console.WriteLine($"Title: {article.Content_Title}"); } }
Console.WriteLine("-DONE-"); } } } |
ApplicationDbContext.cs
using DataModels; using Microsoft.EntityFrameworkCore; namespace Database { public class ApplicationDbContext : DbContext { public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options): base(options) { } public DbSet<ArticleDbModel> tbl_Articles { get; set; } } } |
Und eine angebundene Tabelle
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema;
namespace DataModels { [Table(name: "tbl_Articles")] public class ArticleDbModel { [Key] public string GuidArticle { get; set; } = string.Empty; //guid
//[MaxLength(36)] //public string? GuidUser { get; set; } = string.Empty; //guid max 36 charakters
//[Required] //[MaxLength(255)] public string? Content_Title { get; set; } = string.Empty;
//public string? Content_Text { get; set; } = string.Empty; //public string? Content_Html { get; set; } = string.Empty;
//[MaxLength(450)] //public string? Folder { get; set; } = string.Empty; //[MaxLength(255)] //public string? Keywords { get; set; } = string.Empty; //public DateTime DateCreated { get; set; } = DateTime.Now; //public DateTime DateEdit { get; set; } = DateTime.Now; } }
|
Über den Nuget Packet Manager sind angebunden
Entity Framework Core 6 und EntityFrameworkCore.SqlServer 6
Error
System.Data.SqlTypes.SqlNullValueException: 'Data is Null. This method or property cannot be called on Null values.'