tgstation-server 6.12.0
The /tg/station 13 server suite
Loading...
Searching...
No Matches
ModelBuilderExtensions.cs
Go to the documentation of this file.
1using System;
2using System.ComponentModel.DataAnnotations;
3using System.Linq.Expressions;
4using System.Reflection;
5
6using Microsoft.EntityFrameworkCore;
7
9
11{
16 {
24 public static ModelBuilder MapMySqlTextField<TEntity>(
25 this ModelBuilder modelBuilder,
26 Expression<Func<TEntity, string?>> expression)
27 where TEntity : class
28 {
29 var property = modelBuilder
30 .Entity<TEntity>()
31 .Property(expression);
32 property
33 .HasCharSet("utf8mb4");
34
35 var propertyInfo = GetPropertyFromExpression(expression);
36 var stringLengthAttribute = propertyInfo.GetCustomAttribute<StringLengthAttribute>();
37
38 if (stringLengthAttribute?.MaximumLength == Limits.MaximumStringLength)
39 property.HasColumnType("longtext");
40
41 return modelBuilder;
42 }
43
50 static PropertyInfo GetPropertyFromExpression<TEntity>(Expression<Func<TEntity, string?>> expression)
51 {
52 MemberExpression memberExpression;
53
54 // this line is necessary, because sometimes the expression comes in as Convert(originalexpression)
55 if (expression.Body is UnaryExpression unaryExpression)
56 if (unaryExpression.Operand is MemberExpression unaryAsMember)
57 memberExpression = unaryAsMember;
58 else
59 throw new ArgumentException("Cannot get property from expression!", nameof(expression));
60 else if (expression.Body is MemberExpression)
61 memberExpression = (MemberExpression)expression.Body;
62 else
63 throw new ArgumentException("Cannot get property from expression!", nameof(expression));
64
65 return (PropertyInfo)memberExpression.Member;
66 }
67 }
68}
Sanity limits to prevent users from overloading.
Definition Limits.cs:9
const int MaximumStringLength
Length limit for strings in fields.
Definition Limits.cs:13
Extension methods for the ModelBuilder class.
static ModelBuilder MapMySqlTextField< TEntity >(this ModelBuilder modelBuilder, Expression< Func< TEntity, string?> > expression)
Set a given TEntity 's property's column charset to "utf8mb4". Only for use with the MySQL/MariaDB pr...
static PropertyInfo GetPropertyFromExpression< TEntity >(Expression< Func< TEntity, string?> > expression)
Get the PropertyInfo pointed to by an expression .