C
C#2y ago
Alerin

✅ Can I create a Liststring in mssql ef core?

my models:
public class Template
{
public int Id { get; set; }
public string Title { get; set; } = string.Empty; // Nazwa szablonu
public string Content { get; set; } = string.Empty;
public string Description { get; set; } = string.Empty;
public List<string> HashTags{ get; set; } = new();
}
public class Template
{
public int Id { get; set; }
public string Title { get; set; } = string.Empty; // Nazwa szablonu
public string Content { get; set; } = string.Empty;
public string Description { get; set; } = string.Empty;
public List<string> HashTags{ get; set; } = new();
}
Can I save data like this without creating a new table? This is a template, it will really be used little and I don't care about performance.
6 Replies
Angius
Angius2y ago
If you use Postgres, sure If you use a different database... I guess you can write a type converter that'll let you store it as a JSON string, or comma-delimited, or some such
Alerin
AlerinOP2y ago
I use mssql, recently I saw that they introduced this possibility.
Alerin
AlerinOP2y ago
.NET Blog
Announcing Entity Framework Core 7 RC2: JSON Columns
Announcing Entity Framework Core 7 (EF7) RC2 featuring JSON column mapping.
Alerin
AlerinOP2y ago
I found something like this but I don't understand how to use it on a simple string list.
modelBuilder.Entity<Template>().OwnsOne(
author => author.HashTags, ownedNavigationBuilder =>
{
ownedNavigationBuilder.ToJson();
});
modelBuilder.Entity<Template>().OwnsOne(
author => author.HashTags, ownedNavigationBuilder =>
{
ownedNavigationBuilder.ToJson();
});
not work
modelBuilder.Entity<Template>()
.Property(e => e.HashTags)
.HasConversion(
v => JsonSerializer.Serialize(v, (JsonSerializerOptions)null!),
v => JsonSerializer.Deserialize<List<string>>(v, (JsonSerializerOptions)null!),
new ValueComparer<ICollection<string>>(
(c1, c2) => c1.SequenceEqual(c2),
c => c.Aggregate(0, (a, v) => HashCode.Combine(a, v.GetHashCode())),
c => (ICollection<string>)c.ToList()));
modelBuilder.Entity<Template>()
.Property(e => e.HashTags)
.HasConversion(
v => JsonSerializer.Serialize(v, (JsonSerializerOptions)null!),
v => JsonSerializer.Deserialize<List<string>>(v, (JsonSerializerOptions)null!),
new ValueComparer<ICollection<string>>(
(c1, c2) => c1.SequenceEqual(c2),
c => c.Aggregate(0, (a, v) => HashCode.Combine(a, v.GetHashCode())),
c => (ICollection<string>)c.ToList()));
Work
Accord
Accord2y ago
Closed!
Want results from more Discord servers?
Add your server