使用ADO.NET实体框架从另一个访问一个对象

时间:2012-01-24 15:34:05

标签: c# entity-framework ado.net

我有以下代码:

using (var db = new IntDB())
{
    var subscription =
        (from s in db.Subscription
         where s.SubsciptionId == subscriptionId
         select s).FirstOrDefault();
    if (subscription != null)
    {
        db.DeleteObject(subscription);
        db.SaveChanges();

        EntityKeyMember articleId = (EntityKeyMember)subscription.ArticleReference
                                 .EntityKey.EntityKeyValues.GetValue(0);
        var article = (from a in db.Article
                       where a.ArticleId == (int)articleId.Value
                       select a).FirstOrDefault();
        if (!String.IsNullOrEmpty(article.WebUrl) && article.WebUrl.Equals(@"/ExploderLists"))
        {
            var lstAppIntrfc = new ListAppInterface();
            // the articleId is stored in the entity key here, the article object hasn't been instanicated
            // so it's easier to just get it from the EntityKey.                            
            lstAppIntrfc.RemoveEmailFromListByArticleID((int)articleId.Value, subscription.EmailAddress);
        }
    }
}

这是我的问题。在使用LINQ代码加载Subscription对象后,我发现订阅实例的Article属性为NULL!我可以在订阅实例中找到该文章的entityKey,但我必须运行LINQ来加载我在那里的最终IF语句所需的文章实例。

我刚刚完全退出预订,我不了解如何使用实体对象,或者这是唯一的方法吗?

1 个答案:

答案 0 :(得分:1)

使用Include方法急切加载Article Subscription

using (var db = new IntDB())
{
    var subscription = db.Subscription.Include("Article")
          .Where(s => s.SubsciptionId == subscriptionId).FirstOrDefault();
    if (subscription != null)
    {
        var article = subscription.Article;
        db.DeleteObject(subscription);
        db.SaveChanges();

        if (!String.IsNullOrEmpty(article.WebUrl) && article.WebUrl.Equals(@"/ExploderLists"))
        {
            var lstAppIntrfc = new ListAppInterface();
            // the articleId is stored in the entity key here, the article object hasn't been instanicated
            // so it's easier to just get it from the EntityKey.                            
            lstAppIntrfc.RemoveEmailFromListByArticleID((int)articleId.Value, subscription.EmailAddress);
        }
    }
}