How to store JSON in an entity field with EF Core?

前端 未结 10 509
死守一世寂寞
死守一世寂寞 2020-11-29 17:13

I am creating a reusable library using .NET Core (targeting .NETStandard 1.4) and I am using Entity Framework Core (and new to both). I have an entity class that looks like

10条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-29 18:16

    The comment by @Métoule:

    Be careful with this approach: EF Core marks an entity as modified only if the field is assigned to. So if you use person.Addresses.Add, the entity won't be flagged as updated; you'll need to call the property setter person.Addresses = updatedAddresses.

    made me take a different approach so that this fact is obvious: use Getter and Setter methods, rather than a property.

    public void SetExtendedData(JObject extendedData) {
        ExtendedData = JsonConvert.SerializeObject(extendedData);
        _deserializedExtendedData = extendedData;
    }
    
    //just to prevent deserializing more than once unnecessarily
    private JObject _deserializedExtendedData;
    
    public JObject GetExtendedData() {
        if (_extendedData != null) return _deserializedExtendedData;
        _deserializedExtendedData = string.IsNullOrEmpty(ExtendedData) ? null : JsonConvert.DeserializeObject(ExtendedData);
        return _deserializedExtendedData;
    }
    

    You could theoretically do this:

    campaign.GetExtendedData().Add(something);
    

    But it's much more clear that That Doesn't Do What You Think It Does™.

    If you're using database-first and using some kind of class auto-generator for EF, then the classes will usually be declared as partial, so you can add this stuff in a separate file that won't get blown away the next time you update your classes from your database.

提交回复
热议问题