MVC3 EF4.1 Code-First Lazy Loading


I have this situation:

MVC3 app, with EF4.1 Code-First and SQLCE.


  • Content;
  • Translation;

For each Content Item, there will be N Translations linked by the GUID. So the Content class does not have any refference to the Translation but each translation has a Content property.

The Content class has a NotMapped Translation just to send a single model to the view.

When I populate the data base, I can successfully populate both tables using the GUID as parameter.

But how I can load a Translation from the view? Im new to this stuff like lazyloading, navigation properties, etc.

Resuming, I can populate correctly, but didn't figure out how to load both in a single view. How to load the Translation based on a "locale" parameter.

Can anyone help me on this?



Content class

public class Content
    #region [ Properties ]
    /// <summary>
    /// The GUID
    /// </summary>
    public string GUID { get; set; }

    public string Type { get; set; }

    public Translation Translation { get; set; }

Translation class

public class Translation
    public int ID { get; set; }

    public Content Content { get; set; }

    public string Name { get; set; }

    public string Description { get; set; }

Population code

for (int i = start; i < (start + 2); i++)
            Content c = new Content(1234);
            c.Type = Type.ToString();

            using (ContentContext db = new ContentContext())
                if (!db.Contents.Any(o => o.GUID == c.GUID))

                    c.RegionalInfo.Name = "test";

                    c = db.Contents.Single(o => o.GUID == c.GUID);

    // local list to load on the controller

You can't do it. If you want lazy loading you must expose Translations on your Content. If you want to have only one non mapped translation on the Content you must load it manually (separate query) before you pass the content to the view:

Content content = LoadContent();
content.Translation = context.Translations
                              .Single(t => t.Content.GUID == contentId && t.Name == locale);