Jimmyt1988
Jimmyt1988

Reputation: 21126

List.Add() not working in c# - getter and setter issue?

I've got this property:

public virtual List<FieldImage> Images { get; set; }

If i go and get the class that has this property, from my database using entity like so...

Field field = this.unitOfWork.FieldRepository.GetByID(Convert.ToInt32(fieldID));

and then add an image to the array:

FieldImage fieldImage = new FieldImage()
{
    CreatedAt = dateNow,
    UpdatedAt = dateNow,
    CreatedBy = unitOfWork.UserRepository.GetByID(User.Identity.GetUserId()),
    File = file,
    Field = field
};

field.Images.Add(fieldImage);

and then save the context like so:

this.context.SaveChanges();

All is okay. The images array gets filled up, and the save to database works great.

If i change the property to this:

private List<FieldImage> _images;
public virtual List<FieldImage> Images
{
    get
    {
        return 
            this._images != null ? 
            this._images.Where(x => x.DeletedAt == null).ToList() : 
            new List<FieldImage>();
    }
    set
    {
        this._images = value;
    }
}

And now do the exact thing i was dong before, the field.Images remains empty but no error is made... and ofcourse the database save doesn't occur.

What am i doing wrong?

Edit:

This works, thanks... Looks like i had issue with my if logic:

    private List<FieldImage> _images;
    public virtual List<FieldImage> Images
    {
        get
        {
            if (this._images == null)
            {
                this._images = new List<FieldImage>();
            }

            return this._images;
        }
        set
        {
            this._images = value.Where( x => x.DeletedAt == null ).ToList();
        }
    }

Upvotes: 2

Views: 1063

Answers (2)

D Stanley
D Stanley

Reputation: 152521

Your getter is always returning a new list. When you call

field.Images.Add(fieldImage);

You are getting a newly created list and adding an item to it, but there's no connection to the source data.

Some options:

  • Add an Add method that adds the item to the original list
  • Filter the items when the data is loaded instead of when it' fetched
  • When asking for the property, set the field value (_images) to the filtered list

Upvotes: 2

Roberto Conte Rosito
Roberto Conte Rosito

Reputation: 2098

Why you are doing this kind of operation on your model? You can add another column flagged as "NotMapped" to do the same operation, please read this code:

[NotMapped]
public IEnumerable<FieldImage> NotDeletedImages 
{
    get 
    {
        return this.Images.Where(x => !x.Deleted);
    }
}

I suppose you apply this filter because you want to "display" different data. In this case why you don't use a view model?

Upvotes: 3

Related Questions