This is simple with EF Core.
Model
public partial class Account
{
public int Id { get; set; }
public string Email { get; set; }
public bool? Active { get; set; }
public DateTime? CreatedDate { get; set; }
public string[] Roles { get; set; }
}
In OnModelCreating we use HasConversion to handle Roles array
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.HasAnnotation("Relational:Collation", "SQL_Latin1_General_CP1_CI_AS");
modelBuilder.Entity<Account>()
.Property(e => e.Roles)
.HasConversion(
v => string.Join(',', v),
v => v.Split(',',
StringSplitOptions.RemoveEmptyEntries));
OnModelCreatingPartial(modelBuilder);
}
Example code to add an account
using System;
using AccountsEntityFramework.Models;
using Newtonsoft.Json;
namespace AccountsEntityFramework
{
partial class Program
{
static void Main(string[] args)
{
using var context = new Context.Context();
var account = IncomingAccount();
context.Add(account);
context.SaveChanges();
Console.WriteLine($"Id for new account {account.Id}");
Console.ReadLine();
}
static Account IncomingAccount()
{
Account account = new ()
{
Active = true,
CreatedDate = new DateTime(2013,1,20),
Email = "james@example.com",
Roles = new []{"User", "Admin"}
};
return JsonConvert.DeserializeObject<Account>(
JsonConvert.SerializeObject(account, Formatting.Indented));
}
}
}