0

I have issue in the following code. Below is my model code

public class Comments
{
    public string displayComments { get; set; }

    [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}")]
    public DateTime? dTime { get; set; }

    public int airPortId { get; set; }
}

public class LstComments
{
    private List<Comments> _lstcomment = new List<Comments>();

    public List<Comments> lstCommet
    {
        get
        {
            return _lstcomment;
        }
        set
        {
            _lstcomment = value;
        }
    }
}

and in mycontroller am getting data from EF and adding it to the properties in For loop. Code Below

Comments com = new Comments();
LstComments savedComments = new LstComments();

AirportEntities airPortEntity = new AirportEntities();

var userComments = from c in airPortEntity.AirportComments
                    select c;

//List<Comments> savedComments = new List<Comments>();

foreach (var item in userComments)
{
    com.displayComments = item.Comments;
    com.dTime = item.Time;

    savedComments.lstCommet.Add(com);            
}

My issue is my entire list is getting updated with same records(recently added data)

For eg. foreach 3rd timn updates both 1st and 2nd 3rd item in list with 3rd item data.

What i am doing wrong ?

1
  • yuck... you have some serious naming convention issues :( Commented Feb 26, 2013 at 14:01

2 Answers 2

5

You instantiate Comments outside of the loop. This means there are a bunch of references to the same comment object on the heap. You need to do

Comments com = new Comments(); inside of the foreach. This will create a separate instance on each iteration, instead of just giving the one instance new values.

Sign up to request clarification or add additional context in comments.

2 Comments

@user2067567 If one of our answers helped you, please click the white checkmark next to the answer. It will then turn green. This is accepting the answer as correct so future users with similar problems will know which one worked for you
Yes Steve. I tried to mark it immediately but the rule is that i need to wait for sometime. Done now :)
3

you need to instantiate Comments com = new Comments(); each time in foreach. As for now you just rewrite reference to the same object.

Or which is better to rewrite foreach as:

    foreach (var item in userComments)
    {
        savedComments.lstCommet.Add(
           new Comments()
           {
               com.displayComments = item.Comments,
               com.dTime = item.Time
           });  
    }

1 Comment

Thanks for the quick answer. tat helped

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.