迭代中的linq问题

时间:2011-06-20 07:07:40

标签: c# linq

我在ASP.NET中使用LINQ并且有这样的代码:

for (int i = 0; i <= 2; i++)
{
    IPost post = _postRepository.GetById(1);
    txtTest.Text = post.Title; 
    post.Title = "test" + i.ToString();
}

在每次迭代中我都会跟踪post.Title,但它的值是先前的值而不是数据库中的值:

txtTest.Text:
    i=0 => what is in database
    i=1 => test0
    i=2 => test1

我想解释一下我的主要问题: 我有一个帖子课:

public class Post
{
    Long Id { get; set; }

    long Author { get; set; }

    string Title { get;  set; }

    string Excerpt { get; set; }

    string Content { get; set; }        

    ICollection<ShareLink> ShareLinks
    {
        get
        {
            IShareLinkRepository _shareLinkRepository = null;
            _shareLinkRepository = ObjectFactory.GetInstance<IShareLinkRepository>();

            ICollection<ShareLink> shareLInks =_shareLinkRepository.Get();

            foreach (IShareLink shareLink in shareLInks)
            {
                System.Web.HttpContext context = System.Web.HttpContext.Current;
                string newUrl = context.Request.Url.Scheme +
                    "://" + context.Request.Url.Authority +
                    context.Request.ApplicationPath.TrimEnd('/') + "/posts.aspx?p="
                    + this.Id;

                url.Replace("{title}", this.Tilte).Replace("{url}", newUrl);

            }

            return shareLInks;
        }
    }
}

和ShareLink是:

public class ShareLink     
{
    long Id { get; set; }

    string Url { get; set; }

    string Name { get; set; }

    string Image { get; set; }
}

ShareLink.url的值如下所示:http://digg.com/submit?phase=2&url= {url}&amp; title = {title} 在帖子类的ShareLinks字段中,ShareLinks.url的所有值首先发布ShareLinks值

2 个答案:

答案 0 :(得分:5)

更改IPost post = _postRepository.GetById(1)

IPost post = _postRepository.GetById(i+1);

(根据以下评论添加)

IPost newPost = new IPost();  // OR however you have managed to get your existing object

IEnumerable<IPost> allPosts = _postRepository.All();

foreach ( var post in allPosts)
{
     post.Url = String.Format("digg.com/submit?phase=2&url={0}&title={1}", newPost.Url, newPost.Title);
     post.Save();
}   

答案 1 :(得分:0)

在这一行

post.Title = "test"+i.ToString();

更改存储库中帖子的标题。因此,在随后的迭代中读取该值。请记住,变量post不包含存储库中值的副本;它是存储库中当前值引用

这就是详细情况:

迭代0:

post = value 1 from repository (Title = "what is in database")
txtTest.Text = "what is in database"
post.Title = "test0" (changes the value in the repository!)

迭代1:

post = value 1 from repository (Title = "test0")
txtTest.Text = "test0"
post.Title = "test1" (changes the value in the repository!)

迭代2:

post = value 1 from repository (Title = "test1")
txtTest.Text = "test1"
post.Title = "test2" (changes the value in the repository!)