Skip to content

Instantly share code, notes, and snippets.

@adams85
Last active September 13, 2018 11:16
Show Gist options
  • Save adams85/b4712cd6c6b59403d3f1c6fb4e055d70 to your computer and use it in GitHub Desktop.
Save adams85/b4712cd6c6b59403d3f1c6fb4e055d70 to your computer and use it in GitHub Desktop.
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Console;
namespace test
{
public abstract class EntityBase
{
public int Id { get; set; }
public byte[] RowVersion { get; set; }
}
public abstract class ParentUnit : EntityBase
{
public string Name { get; set; }
}
public class ChildArea1 : ParentUnit
{
public string Description { get; set; }
}
public class ChildArea2 : ParentUnit
{
public string AreaCode { get; set; }
}
class DataContext : DbContext
{
static readonly LoggerFactory loggerFactory = new LoggerFactory(new[] {
new ConsoleLoggerProvider((_, level) => level >= LogLevel.Information, true)
});
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseLoggerFactory(loggerFactory);
optionsBuilder.UseSqlite("FileName=data.db");
base.OnConfiguring(optionsBuilder);
}
protected override void OnModelCreating(ModelBuilder builder)
{
builder.Entity<ParentUnit>().Property(x => x.Name).IsRequired();
// Rowversion is defined on EntityBase and inherited by all children
builder.Entity<ChildArea1>().Property(x => x.RowVersion).IsRowVersion();
builder.Entity<ChildArea2>().Property(x => x.RowVersion).IsRowVersion();
builder.Entity<ChildArea2>().Property(x => x.AreaCode).IsRequired();
base.OnModelCreating(builder);
}
public DbSet<ParentUnit> ParentUnit { get; set; }
public DbSet<ChildArea1> ChildArea1 { get; set; }
public DbSet<ChildArea2> ChildArea2 { get; set; }
}
}
using System;
namespace test
{
class Program
{
static void Main(string[] args)
{
using (var ctx = new DataContext())
{
ctx.Database.EnsureDeleted();
ctx.Database.EnsureCreated();
ctx.ChildArea1.Add(new ChildArea1 { Name = "Area", Description = "desc" });
ctx.ChildArea2.Add(new ChildArea2 { Name = "Area", AreaCode = "1" });
ctx.SaveChanges();
}
using (var ctx = new DataContext())
{
foreach (var unit in ctx.ParentUnit)
Console.WriteLine($"Id = {unit.Id}, Type = {unit.GetType().Name}");
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment