สร้างโปรเจค / ติดตั้ง Library
dotnet new console --language C# --output src/Library
dotnet add src/Library/Library.csproj \
Npgsql.EntityFrameworkCore.PostgreSQL
เขียน Entity class ชื่อ Library โดยมีฟิลด์ Books
เป็น List ที่ต้องการเก็บลงฐานข้อมูล
public class Library {
[Key]
public int Id { set; get; }
public List<string> Books { set; get; }
}
เขียน Context โดยเพิ่ม ValueConvert ให้กับฟิลด์ Books
ดังนี้
public class LibraryContext : DbContext {
public DbSet<Library> Libraries { set; get; }
public LibraryContext(DbContextOptions options)
: base(options) { } protected override void
OnModelCreating(ModelBuilder builder) { var splitStringConverter =
new ValueConverter<List<string>, string>(
v => string.Join(";", v),
v => v.Split(new[] { ';' }).ToList()
);
builder.Entity<Library>()
.Property(nameof(Library.Books))
.HasConversion(splitStringConverter);
}
}
ตัวอย่างการ Insert ข้อมูล
var options = new DbContextOptionsBuilder()
.UseNpgsql("Host=localhost;User Id=postgres;Password=1234;Database=Library")
.Options;using var context = new LibraryContext(options);
context.Database.EnsureCreated();var library = new Library {
Books = new List<string> {
"Book 1",
"Book 2",
"Book 3"
}
};
context.Libraries.Add(library);
context.SaveChanges();
ในฐานข้อมูล List จะถูกแปลงเป็น String โดยขั้นด้วยเครื่องหมาย ;
ดังนี้