Die Modelle:
Code: Select all
public enum ExampleEnum
{
Mecury,
Venus,
Earth,
Mars
}
internal class ExampleEntity
{
public int id { get; set; }
[Required]
public ExampleEnum Val { get; set; }
}
internal class EFContext : DbContext
{
public EFContext(DbContextOptions options) : base(options)
{
}
public virtual DbSet Ents { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity(entity =>
{
entity.Property(e => e.Val).HasDefaultValue(ExampleEnum.Earth);
});
}
}
Code: Select all
class Program
{
private static DbConnection CreateInMemoryDatabase()
{
var connection = new SqliteConnection("Filename=:memory:");
connection.Open();
return connection;
}
static void Main(string[] args)
{
var ContextOptions = new DbContextOptionsBuilder()
.UseSqlite(CreateInMemoryDatabase())
.Options;
using (var context = new EFContext(ContextOptions))
{
context.Database.EnsureDeleted();
context.Database.EnsureCreated();
}
using (var db = new EFContext(ContextOptions))
{
var newEntity = new ExampleEntity
{
Val = ExampleEnum.Mecury,
};
db.Ents.Add(newEntity);
db.SaveChanges();
}
using (var db = new EFContext(ContextOptions))
{
var savedEnt = db.Ents.First();
Console.WriteLine(savedEnt.Val.ToString());
}
}
}
Code: Select all
var newEntity = new ExampleEntity
{
Val = ExampleEnum.Mecury,
};
db.Ents.Add(newEntity);
db.SaveChanges();
newEnttity.Val = ExampleEnum.Mecury;
db.SaveChanges()
Mobile version