Reputation: 15475
Environment:
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="3.1.7" />
Database table:
Id (Primary key)
Settings (nvarchar(max) contains the nested json)
DateCreated datetime
DateModified datetime
I'm using the following EF dynamic call in c#:
return Context.Set<T>().FromSqlRaw($"EXEC {spName}").ToList();
C# object to deserialize to:
public class UserSetting
{
public int ID { get; set; }
public MyClass SettingData { get; set; }
public DateTime DateCreated { get; set; }
public DateTime? DateModified { get; set; }
public class MyClass
{
public string MyProperty { get; set; }
}
}
Errors I ran into:
MyClass needs to be Keyless
When I fix that I get another error:
There is no relationship between UserSetting and MyClass
Is it possible for Entity Framework to automatically deserialize MyClass
type for property SettingData
in UserSetting
class?
Update
{
"MyClass": {
"MyProperty": "Hello World"
}
}
Update 2
I'm testing update database table for only the SettingData property, is the following snippet correct for passing to SQL Server stored procedure? Because I'm getting error
new SqlParameter() { ParameterName = "@settingData", SqlDbType = SqlDbType.NVarChar, Value = userSettingToUpdate.SettingData
Upvotes: 0
Views: 383
Reputation: 1733
"Value Conversions" let you map database fields to object and vise versa :
modelBuilder
.Entity<UserSetting>()
.Property(e => e.SettingData )
.HasConversion(
v => JsonConvert.SerializeObject(v, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }),
v => JsonConvert.DeserializeObject<MyClass>(v, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }));
Upvotes: 3