Rod
Rod

Reputation: 15475

Entity Framework - stored procedure call for record that contains nested json object: how to handle deserialize

Environment:

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"
  }
}  

enter image description here

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 

enter image description here

Upvotes: 0

Views: 383

Answers (1)

Mojtaba Tajik
Mojtaba Tajik

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

Related Questions