C
C#2y ago
Táuròs

✅ Dataannotations

Hi, is there a way in C# to Build a custom Dataannotation for SQL Columns? With the [Default()] Annotation it is not possible to set the Sql Column to a NEWID() oder GETDATE() Default Value.
11 Replies
Angius
Angius2y ago
EF Core?
Táuròs
TáuròsOP2y ago
Yes
Angius
Angius2y ago
With fluent config, you'd use .HasDefaultValueSql() So maybe there's some [DefaultSql] or [DefaultFromSql] attribute
Táuròs
TáuròsOP2y ago
i did this in the OnModelCreating Method modelBuilder.Entity<DomainModel>().Property(p => p.Id).HasDefaultValueSql("NEWID()"); but if there is a way to build a Custom Dataannotation for this it would be awesome, so i can use [SQLDefault(NEWID())] in the model
Angius
Angius2y ago
¯\_(ツ)_/¯ I never use attributes for configuring my models Only fluent config
Táuròs
TáuròsOP2y ago
there is no [DefaultSql] or [DefaultFromSql] attribute thanks
Jimmacle
Jimmacle2y ago
data annotations are generally more limited than the fluent API, i'm sure you could extend EF Core to do what you want but it would be more complicated i also only use the fluent API for this reason
Táuròs
TáuròsOP2y ago
Thanks all, I have now a solution to use Dataannotations for SQL Default Values i will share it here for you.
Táuròs
TáuròsOP2y ago
A New File called DefaultVauleSql I placed it in a Folder Called Dataannotations [AttributeUsage(AttributeTargets.Property)] public class DefaultValueSqlAttribute : Attribute { public string DefaultValueSql { get; private set; } = ""; public DefaultValueSqlAttribute(string defaultValueSql) { DefaultValueSql = defaultValueSql; } } In the DataContext Class on the Method OnModelCreation i call OnModelCreatingAddDefaultSqlValues(modelBuilder);
Táuròs
TáuròsOP2y ago
And this is the Function in the DataContext Class private void OnModelCreatingAddDefaultSqlValues(ModelBuilder modelBuilder) { var assemblyName = "SelfService.Portal.Core.API"; var nameSpace = "SelfService.Portal.Core.API.Models"; var asm = Assembly.Load(assemblyName); List<Type> types = asm.GetTypes().Where(p => p.Namespace == nameSpace).ToList(); var dbSets = typeof(DataContext).GetProperties().Where(p => p.PropertyType.Name.ToLower().Contains("dbset")).ToList(); List<Type> dbSetTypes = new List<Type>(); foreach (PropertyInfo pi in dbSets) { dbSetTypes.Add(pi.PropertyType.GetGenericArguments()[0]); } foreach (Type t in types) { if (typeof(BaseModel).IsAssignableFrom(t) && t.Name != nameof(BaseModel) && dbSetTypes.Contains(t)) { var properties = t.GetProperties().ToList(); foreach (var p in properties) { var att = p.GetCustomAttribute<DefaultValueSqlAttribute>(); if (att != null) { modelBuilder.Entity(t).Property(p.Name).HasDefaultValueSql(att.DefaultValueSql); } } } } }
Accord
Accord2y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.

Did you find this page helpful?