开发者

MVC3 EF4.1 Code-First Lazy Loading

I have this situation:

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

Entities:

  • 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?

Thanks.

UPDATE: CODE

Content class

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

    public string Type { get; set; }


    [NotMapped]
    public Translation Translation { get; set; }
    #endregion
}

Translation class

public class Translation
{
  开发者_运维技巧  [Key]
    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.PopulateInfo(Locale);
                    db.Contents.Add(c);

                    c.RegionalInfo.Name = "test";
                    db.Translations.Add(c.Translation);

                    db.SaveChanges();
                }
                else
                {
                    c = db.Contents.Single(o => o.GUID == c.GUID);
                }
            }

    // local list to load on the controller
            Contents.Add(c);
        }


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);


First I think your Content entity should have a ICollection of Translation to correctly represent the 1:N relation between Translation and Content. Second if you want to retrieve the correct Translation and Content in one query start at the translation like so:

var translation = context.Translations.Include("Content").Single(t => t.Content.GUID == contentId && t.Name == locale);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜