Search code examples
entity-frameworkentity-framework-4.1ef-code-firstentity-relationshipcode-first

Add object to context and get properties from the relationship


I made a while ago some code that adds an object to my table with entity framework code first.

Context.Reactions.Attach(reaction);
Context.SaveChanges();

After that I used a relationship called Profile to get the name of the user that posted the reaction.

reaction.Profile.FirstName + " " + reaction.Profile.LastName

Now after a while, I get a nullreference on Profile when I try to get the name of the person.

So why can't I add an object and after that use the Profile relationship?

Edit: I'm getting the nullreference on the Profile relation property. So reaction.Profile says that is null. It is the same instance. Entity Framework has given me an id for the reaction so the savechanges() works. The line for getting the FirstName is the line directly after the SaveChanges so the context couldn't be disposed right?

Complete code:

var reaction = new Reaction()
                                {
                                    Text = reactionText,
                                    ProfileId = CurrentProfileId,
                                    PostedOn = DateTime.Now
                                };

                    //Save changes to the backend
                    context.Reactions.Add(reaction);
                    context.SaveChanges();

                    return Json(new
                    {
                        Id = reaction.Id,
                        ReactionType = reactionType,
                        ReactionTypeId = reactionTypeId,
                        ReactionText = reaction.Text,
                        PostedOn = reaction.PostedOn.ToString("G"),
                        ProfileName = string.Format("{0} {1}", reaction.Profile.FirstName, reaction.Profile.LastName)
                    });

I even tryed with this code around it.

using (var context = new SeeTingsContext())
                {
                    context.Configuration.LazyLoadingEnabled = true;


                }

Solution

  • I didn't quite get you when I read after a while. Does this mean you get the relation object first, and then it suddenly becomes null?
    My guess is:

    • You have not set LazyLoadingEnabled to true for the context you're working on.
    • Your context is disposed and thus you cannot use it to get the relationship. Note that you can use Lazy loading while your context still exists.

    Update: Based on the comments, try to load the relation explicitly and see if you can get the profile:

    if (!context.Entry(reaction).Reference(r => r.Profile).IsLoaded)
    {
        context.Entry(reaction).Reference(r => r.Profile).Load();
    }  
    

    If you cannot get profile using this way, I suppose there's something wrong with your mapping.