CSharp · Console
// @nuget: Microsoft.EntityFrameworkCore.SqlServer
// @nuget: Z.EntityFramework.Extensions.EFCore
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;
public class Program
{
public static void Main()
{
using (var context = new EntityContext())
{
context.Database.EnsureCreated();
}
using (var context = new EntityContext())
{
context.Animals.Add(new Cat() { Name = "Nala", DateOfBirth = new DateTime(2024, 11, 01), IsIndoor = true, LivesRemaining = 8 });
context.Animals.Add(new Dog() { Name = "Bengi", DateOfBirth = new DateTime(2017, 04, 01), Breed = "Anything", IsGoodBoy = true });
context.SaveChanges();
}
using (var context = new EntityContext())
{
context.Database.OpenConnection();
var dtAnimals = QueryTable((SqlConnection)context.Database.GetDbConnection(), "Animals");
FiddleHelper.WriteTable("1 - Animals", dtAnimals);
context.Database.CloseConnection();
}
}
public static DataTable QueryTable(SqlConnection connection, string tableName)
{
using var command = connection.CreateCommand();
command.CommandText = $"SELECT * FROM {tableName}";
using var adapter = new SqlDataAdapter(command);
var dt = new DataTable();
adapter.Fill(dt);
return dt;
}
public class EntityContext : DbContext
{
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(new SqlConnection(FiddleHelper.GetConnectionStringSqlServer()));
base.OnConfiguring(optionsBuilder);
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Animal>().UseTphMappingStrategy();
modelBuilder.Entity<Cat>();
modelBuilder.Entity<Dog>();
base.OnModelCreating(modelBuilder);
}
public DbSet<Animal> Animals { get; set; }
}
public abstract class Animal
{
public int Id { get; set; }
public string? Name { get; set; }
public DateTime DateOfBirth { get; set; }
}
public class Cat : Animal
{
public bool IsIndoor { get; set; }
public int LivesRemaining { get; set; }
}
public class Dog : Animal
{
public string? Breed { get; set; }
public bool IsGoodBoy { get; set; }
}
}