Использование ADO.NET Entity Framework для доступа к одному объекту из другого - PullRequest
0 голосов
/ 24 января 2012

У меня есть следующий код:

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

и вот мой вопрос.После загрузки объекта Subscription с помощью кода LINQ я обнаружил, что свойство Article экземпляра подписки равно NULL!Я могу найти entityKey для статьи в экземпляре подписки, но затем мне нужно запустить LINQ, чтобы загрузить экземпляр статьи, который мне нужен для заключительного оператора IF.

Я только что полностью отключился отРезервирование здесь, и я не понимаю, как использовать объекты сущностей, или это единственный способ сделать это?

1 Ответ

1 голос
/ 24 января 2012

Используйте метод 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);
        }
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...