✅ 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
EF Core?
Yes
With fluent config, you'd use
.HasDefaultValueSql()
So maybe there's some [DefaultSql]
or [DefaultFromSql]
attributei 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
¯\_(ツ)_/¯
I never use attributes for configuring my models
Only fluent config
there is no [DefaultSql] or [DefaultFromSql] attribute
thanks
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
Thanks all, I have now a solution to use Dataannotations for SQL Default Values i will share it here for you.
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);
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);
}
}
}
}
}
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.