If you like Attributes
(like me) and you're using EF Core. You could use the following approach.
First, Create an attribute to mark private or properties:
using System;
using System.ComponentModel.DataAnnotations.Schema;
...
[System.AttributeUsage(AttributeTargets.Property, Inherited = true, AllowMultiple = false)]
public sealed class ShadowColumnAttribute : ColumnAttribute
{
public ShadowColumnAttribute() { }
public ShadowColumnAttribute(string name): base(name) { }
}
public static class ShadowColumnExtensions
{
public static void RegisterShadowColumns(this ModelBuilder builder)
{
foreach (var entity in builder.Model.GetEntityTypes())
{
var properties = entity.ClrType
.GetProperties(BindingFlags.Instance | BindingFlags.NonPublic)
.Select(x => new { prop = x, attr = x.GetCustomAttribute<ShadowColumnAttribute>() })
.Where(x => x.attr != null);
foreach (var property in properties)
entity.AddProperty(property.prop);
}
}
}
Then, mark the properties you would like to stay private.
public class MyEntity
{
[Key]
public string Id { get; set; }
public bool SomeFlag { get; set; }
public string Name => SomeFlag ? _Name : "SomeOtherName";
[ShadowColumn(nameof(Name))]
string _Name { get; set; }
}
Finally, in your DbContext
, place this at the end of your OnModelCreating
method:
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
// ...
builder.RegisterShadowColumns();
}