Построение и разделение логики запросов в Linq / mvc4 - PullRequest
0 голосов
/ 22 марта 2012

Я пытаюсь отделить свою логику для лучшей читаемости и повторного использования.Я пытаюсь создать лучшее приложение.

Я покажу вам пример работающего контроллера и модели и покажу, куда я пытаюсь перейти.

Это то место, где я до конверсии.

    private IOAuthCredentials credentials = new SessionStateCredentials();
    private MvcAuthorizer auth;
    private TwitterContext twitterCtx;

 public ActionResult Twitter()
    {



        if (credentials.ConsumerKey == null || credentials.ConsumerSecret == null)
        {
            credentials.ConsumerKey = ConfigurationManager.AppSettings["twitterConsumerKey"];
            credentials.ConsumerSecret = ConfigurationManager.AppSettings["twitterConsumerSecret"];
            credentials.OAuthToken = ConfigurationManager.AppSettings["twitterOAuthToken"];
            credentials.AccessToken = ConfigurationManager.AppSettings["twitterAccessToken"];
        }

     auth = new MvcAuthorizer
      {
           Credentials = credentials
       };

       auth.CompleteAuthorization(Request.Url);

       if (!auth.IsAuthorized)
        {
            Uri specialUri = new Uri(Request.Url.ToString());
           return auth.BeginAuthorization(specialUri);
      }





                twitterCtx = new TwitterContext(auth);

                 List<TweetViewModel> friendTweets = (from tweet in twitterCtx.Status
                                                      where tweet.Type == StatusType.Friends
                                                     select new TweetViewModel
                                                   {
                                                         ImageUrl = tweet.User.ProfileImageUrl,
                                                           ScreenName = tweet.User.Identifier.ScreenName,
                                                          Tweet = tweet.Text
                                                      })
        .ToList();

   return View(friendTweets); 

вот класс

public class TweetViewModel
{
    /// <summary>
    /// User's avatar
    /// </summary>
    public string ImageUrl { get; set; }

    /// <summary>
    /// User's Twitter name
    /// </summary>
    public string ScreenName { get; set; }

    /// <summary>
    /// Text containing user's tweet
    /// </summary>
    public string Tweet { get; set; }
}

Я создал папку datacontext и поместил класс данных в

вот класс

  public class TwitterFriend
  {
    private MvcAuthorizer auth;
    public List<TweetViewModel> GetFriends()
    {

      //  private MvcAuthorizer auth;
        using (var twitterCtx = new TwitterContext(auth))
        {

            var friendTweets = (from tweet in twitterCtx.Status
                                                 where tweet.Type == StatusType.Friends
                                                 select new TweetViewModel
                                                 {
                                                     ImageUrl = tweet.User.ProfileImageUrl,
                                                     ScreenName = tweet.User.Identifier.ScreenName,
                                                     Tweet = tweet.Text
                                                 })
            .ToList();

            return friendTweets;
         }
     }

Затем я попытался создать метод List для создания экземпляра списка (не работает)

    public List<TweetViewModel> GetFriendTweets()
    {
        List<TweetViewModel> friends = (List<TweetViewModel>)(new TwitterFriend());
        // friends.ToList();

        return friends.ToList();
    }
}

Затем я бы поставил список извлечения из метода

Getfriends ():

Извините, если я много чего вставил, я пытаюсь спроектировать и сделать правильное приложение, в котором мне не нужно переделывать всю логику, потому что я знал, что могу попасть в эти ловушки.

Могу ли я получитьнекоторая помощь в исправлении этого.Я не думаю, что это сложный сценарий.

Исправленный ответ для других, если им нужна помощь, приведен ниже!Спасибо !!

Просто класс данных

      public List<TweetViewModel> GetFriends()
       //  public List<Status> GetFriends()
        {
        using (var twitterCtx = new TwitterContext(_auth))
         {


            // List<Type> 
            List<Status> friendTweets = (from tweet in twitterCtx.Status
                                         where tweet.Type == StatusType.Friends
                                         select tweet).ToList();

            List<TweetViewModel> friends = new List<TweetViewModel>();            

            foreach (Status item in friendTweets)
            {
                TweetViewModel search2 = new TweetViewModel();
                {
                    search2.ImageUrl = item.User.ProfileImageUrl;
                    search2.ScreenName = item.User.Identifier.ScreenName;
                    search2.Tweet = item.Text;
                }
             friends.Add(search2);
            }


            return friends.ToList();

1 Ответ

0 голосов
/ 22 марта 2012

Добавьте конструктор в класс друзей в Твиттере, где вы вводите MVCAuthorizer.

открытый класс TwitterFriendService {

private readonly MvcAuthorizer _auth;
public TwitterFriend(MvcAuthorizer auth){

_auth = auth;
}

публичный список GetFriends () {

    using (var twitterCtx = new TwitterContext(_auth))
    {

var friendTweets = (из твита в twitterCtx.Status где tweet.Type == StatusType.Friends выберите новую TweetViewModel { ImageUrl = tweet.User.ProfileImageUrl, ScreenName = tweet.User.Identifier.ScreenName, Tweet = Tweet.Text }) .ToList ();

    return friendTweets;
 }

}

и затем на контроллере:

private IOAuthCredentials credentials = new SessionStateCredentials();
    private MvcAuthorizer auth;
    private TwitterContext twitterCtx;

 public ActionResult Twitter()
    {



        if (credentials.ConsumerKey == null || credentials.ConsumerSecret == null)
        {
            credentials.ConsumerKey = ConfigurationManager.AppSettings["twitterConsumerKey"];
            credentials.ConsumerSecret = ConfigurationManager.AppSettings["twitterConsumerSecret"];
            credentials.OAuthToken = ConfigurationManager.AppSettings["twitterOAuthToken"];
            credentials.AccessToken = ConfigurationManager.AppSettings["twitterAccessToken"];
        }

     auth = new MvcAuthorizer
      {
           Credentials = credentials
       };

       auth.CompleteAuthorization(Request.Url);

       if (!auth.IsAuthorized)
        {
            Uri specialUri = new Uri(Request.Url.ToString());
           return auth.BeginAuthorization(specialUri);
      }



    TwitterFriendService twitterFriendService = new TwitterFriendService(auth);
    List<TweetViewModel> friendTweets = twitterFriendService.GetFriends();

       return View(friendTweets);

}

Надеюсь, это поможет

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...