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

本文关键字:一个对象 访问 框架 ADO NET 实体 使用 | 更新日期: 2023-09-27 18:21:20

我有以下代码:

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语句。

我是不是完全脱离了这里的保留,不知道如何使用实体对象,或者这是唯一的方法?

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

使用Include方法将ArticleSubscription一起加载。

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