Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using navigation properties in entity framework code first

Context:

  • Code First, Entity Framework 4.3.1;
  • User ---- Topic, 1 to Many relation;
  • User with public virtual ICollection<Topic> CreatedTopics Navigation Property(Lazy Loading);
  • Topic with public virtual User Creator Navigation Property;
  • DataServiceController : DbDataController<DefaultDbContext>, Web API beta, ASP.NET MVC 4 Beta , Single Page Application;
  • System.Json for Json serialization;
  • Web API Action:

    public IQueryable<Topic> GetTopics()
    {
        // return DbContext.Topics;                   // OK
        return DbContext.Topics.Include("Creator");   //With Exception
    }
    
  • Result: "an unhandled microsoft .net framework exception occurred in w3wp.exe"

The Problem here seems to be: I should not Add Navigation Property in both Entities(Cause Circular Reference?), and if I delete the CreatedTopics Navigation Property in User Class, It will be OK again.

So, In a similar Context like listed above, Here are my questions:

  1. How to deal with Navigation Properties in the situation of 1 to Many relation;
  2. Further more, how about a Many to Many relation, do i have to divide it into two 1 to Many relations;
  3. What is the Best Practices and Precautions of using Navigation Properties?

I Have read many related posts, but still not clear enough :(,

Thanks for any help!

Dean

like image 442
Dean Avatar asked Jul 03 '12 16:07

Dean


People also ask

How do I use navigation properties in Entity Framework?

A navigation property is an optional property on an entity type that allows for navigation from one end of an association to the other end. Unlike other properties, navigation properties do not carry data. A navigation property definition includes the following: A name.

How do I load a navigation property in Entity Framework?

Entity Framework Core allows you to use the navigation properties in your model to load related entities. There are three common O/RM patterns used to load related data. Eager loading means that the related data is loaded from the database as part of the initial query.

What is navigation property in EF core?

Navigation property: A property defined on the principal and/or dependent entity that references the related entity. Collection navigation property: A navigation property that contains references to many related entities.

Which property in the Entity Framework provides a way to navigate an association between two entity?

Navigation properties provide a way to navigate an association between two entity types. Every object can have a navigation property for every relationship in which it participates.


1 Answers

This is not a problem of code first or EF - it is a problem of serialization. Simply the serializer used to convert your object graph to some representation passed in a Web API message is not able to work with circular references by default. Depending on the message format you want to use Web API uses different serializers by default - here is more about default serializers used by Web API and about the way how to change it. The following text suppose that you are using DataContractJsonSerializer or DataContractSerializer (should be default for XML serialization) but the same is possible for JSON.NET (should be default for JSON serialization - JSON serialization can be switched to DataContractJsonSerializer but the default serializer is better).

So what you can do? You can tell the serializer that it should track those circular references by marking your classes with DataContract(IsReference = true) and each passed property with DataMember attribute (check the linked article for description how to achieve it with JSON.NET). This will allow serializer correctly recognizing cycles and the serialization will in theory succeed. In theory because this also demands to not using lazy loading. Otherwise you can serialize much more data than you expected (in some catastrophic scenarios it can lead to serializing whole content of your database).

When you serialize entity graph with lazy loading enabled you serailze a Topic and its Creator but serialization will also visit CreatedTopics property => all related topics are lazy loaded and processed by serialization and serialization continues to visit Creator of all newly loaded topics! This process continues until there is no other object to lazy load. Because of this you should never use lazy loading when serializing entities.

Other option is to exclude back reference from serialization. You just need to serialize Creator. You don't need to serialize CreatedTopics so you can mark the property with IgnoreDataMember attribute (JsonIgnore for JSON.NET). The problem is that if you also have Web API action for returning User with all his CreateTopics this will not work because of the attribute.

The last option is not using entities. This option is usually used in web services where you create special DTO objects satisfying requirements for specific operation and you handle conversion between entities and DTOs inside the operation (possible with help of some tool like AutoMapper).

There is no difference between handling one-to-one, one-to-many, or many-to-many relations. If you have navigation properties on both sides you must always deal with this problem.

like image 58
Ladislav Mrnka Avatar answered Sep 19 '22 06:09

Ladislav Mrnka