Skip to content

Instantly share code, notes, and snippets.

@rowanmiller
Last active July 19, 2016 20:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rowanmiller/52cd1ffb8ba11889af366ed3114c8a75 to your computer and use it in GitHub Desktop.
Save rowanmiller/52cd1ffb8ba11889af366ed3114c8a75 to your computer and use it in GitHub Desktop.
EF Core | Custom Model Validation Rules
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Internal;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
namespace Demo
{
class Program
{
static void Main(string[] args)
{
var serviceProvider = new ServiceCollection()
.AddEntityFrameworkSqlServer()
.AddScoped<RelationalModelValidator, MyValidator>()
.BuildServiceProvider();
var options = new DbContextOptionsBuilder()
.UseInternalServiceProvider(serviceProvider)
.Options;
using (var context = new TestContext(options))
{
context.Database.EnsureCreated();
context.Products.ToList();
}
}
}
public class MyValidator : RelationalModelValidator
{
public MyValidator(
ILogger<RelationalModelValidator> loggerFactory,
IRelationalAnnotationProvider relationalExtensions,
IRelationalTypeMapper typeMapper)
: base(loggerFactory, relationalExtensions, typeMapper)
{ }
public override void Validate(IModel model)
{
base.Validate(model);
var longTables = model.GetEntityTypes()
.Where(e => e.Relational().TableName.Length > 30)
.ToList();
if(longTables.Any())
{
throw new NotSupportedException(
"The following types are mapped to table names that exceed 30 characters; "
+ string.Join(", ", longTables.Select(e => $"{e.ClrType.Name} ({e.Relational().TableName})")));
}
var longColumns = model.GetEntityTypes()
.SelectMany(e => e.GetProperties())
.Where(p => p.Relational().ColumnName.Length > 30)
.ToList();
if (longColumns.Any())
{
throw new NotSupportedException(
"The following properties are mapped to column names that exceed 30 characters; "
+ string.Join(", ", longColumns.Select(p => $"{p.DeclaringEntityType.Name}.{p.Name} ({p.Relational().ColumnName})")));
}
}
}
public class TestContext : DbContext
{
public TestContext(DbContextOptions options)
: base(options)
{ }
public DbSet<Product> Products { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=Test;Trusted_Connection=True;");
}
}
[Table("ThisTableHasOneVeryCrazySillyLongName")]
public partial class Product
{
public int Id { get; set; }
[Column("ThisColumnHasOneVeryCrazySillyLongName")]
public string Name { get; set; }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment