Feb 17 2025
public class Vehicle
{
public int Id { get; set; }
public string Model { get; set; } = string.Empty;
}
public class Car : Vehicle
{
public int NumberOfDoors { get; set; }
}
public class Bike : Vehicle
{
public bool HasGear { get; set; }
}
public class AppDbContext : DbContext
{
public DbSet<Vehicle> Vehicles { get; set; }
public DbSet<Car> Cars { get; set; }
public DbSet<Bike> Bikes { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer("your_connection_string");
}
}
dotnet ef migrations add InitialCreate
dotnet ef database update
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Vehicle>()
.HasDiscriminator<string>("VehicleType")
.HasValue<Car>("CarType")
.HasValue<Bike>("BikeType");
}
var vehicles = context.Vehicles.ToList();
var cars = context.Cars.ToList();
SELECT * FROM Vehicles WHERE VehicleType = 'CarType';
var bikes = context.Bikes.ToList();
SELECT * FROM Vehicles WHERE VehicleType = 'BikeType';
var bike = context.Bikes.FirstOrDefault(b => b.Id == 2);
if (bike != null)
{
var car = new Car
{
Id = bike.Id, // Keep the same ID
Model = bike.Model,
NumberOfDoors = 4
};
context.Bikes.Remove(bike);
context.Cars.Add(car);
context.SaveChanges();
}
public enum VehicleType
{
Unknown = 0,
Car = 1,
Bike = 2
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Vehicle>()
.HasDiscriminator<VehicleType>("VehicleType")
.HasValue<Car>(VehicleType.Car)
.HasValue<Bike>(VehicleType.Bike);
}
modelBuilder.Entity<Car>().ToTable("Cars");
modelBuilder.Entity<Bike>().ToTable("Bikes");
1. Design Patterns that Deliver
This isn’t just another design patterns book. Dive into real-world examples and practical solutions to real problems in real applications.Check out it here.
Go-to resource for understanding the core concepts of design patterns without the overwhelming complexity. In this concise and affordable ebook, I've distilled the essence of design patterns into an easy-to-digest format. It is a Beginner level. Check out it here.
Every Monday morning, I share 1 actionable tip on C#, .NET & Arcitecture topic, that you can use right away.
Join 15,250+ subscribers to improve your .NET Knowledge.
Subscribe to the TheCodeMan.net and be among the 15,250+ subscribers gaining practical tips and resources to enhance your .NET expertise.