Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do not serialize Entity Framework class references in JSON (ServiceStack.Text library)

As most of the people I've also ran into a problem of circular reference error when serializing (terrible) EF objects to JSON. Doing db.Detach(efObject) helps - but I still get garbage like "EntityKey" outputted.

So I was wondering if there is an option (through JsConfig?) to tell serializer to ignore Properties either through name (EntityKey) or through type (EntityReference<T> or EntityCollection<T>)?

Or will I be forced to ditch EF alltogether and switch to something better (I do not want to manually define ORM classes - I want them automatically generated from DB)?

like image 697
nikib3ro Avatar asked May 07 '26 16:05

nikib3ro


1 Answers

You shouldn't try to re-use Entity Framework types as DTO's since they are by design poor substitutes for DTOs. You should instead map them to special purpose DTO types using ServiceStack's built-in TranslateTo/PopulateFrom mappers (or AutoMapper) and return those.

With that said, use IgnoreDataMember or specify DataMembers on properties you want serialized.

like image 71
mythz Avatar answered May 10 '26 22:05

mythz