I have two entities that are set up with a many-to-many relationship:
Category:
public class Category : IEntityWithRelationships
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public virtual ICollection<User> Users { get; set; }
//Json.NET needs this in order to serialize the object
private RelationshipManager rm;
RelationshipManager IEntityWithRelationships.RelationshipManager
{
get
{
if (rm == null)
rm = RelationshipManager.Create(this);
return rm;
}
}
}
And User:
public class User
{
public int Id { get; set; }
public ICollection<Category> Categories { get; set; }
}
The related objects were loading fine, but then I needed to serialize the category object to Json and Json.Net kept throwing:
The RelationshipManager object could not be serialized. This type of object cannot be serialized when the RelationshipManager belongs to an entity object that does not implement IEntityWithRelationships.
So I implemented the IEntityWithRelationships
interface, but now my related objects are not loading.
I tried a custom ContractResolver
, but I still get the exception above. How can I get my related objects to load?
You can't have that interace in EF
classes because then EF
won't create proxy's => Lazy loading
is turned off. http://msdn.microsoft.com/en-us/library/dd468057.aspx . Actually people advice to turn off LazyLoading
when you have to serialize your entties (of course implementing that interface isn't right way to do this). You should ready more about how to use EntityFramework
with serialization.
You should not implement that interface in code first entities. Implementing that interface violates POCO. It is interface used by "heavy" EF entities and by using it you will loose the way how EF handles POCOs.
I guess the only reason why you want to do it is problem with circular references. You should be able to solve it without specifying any API specific interface.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.