Matt Cashatt
Matt Cashatt

Reputation: 24208

Why is this `set` accessor not working?

I have the following property in my model:

//PRODUCTS
private ICollection<int> _productIds;

[NotMapped]
public ICollection<int> ProductIds
{
    get { return Products.Select(s => s.Id).ToList(); }
    set { _productIds = value; }
}

When my code returns a new instance of this model, the set accessor doesn't seem to take. In other words, I can see that the get accessor is appropriately returning a collection of product ids, but when I attempt to assign using the set, the value is an empty List<int>. For example:

var result = new Application
{
    Id = application.Id,
    . . .
    ProductIds = application.ProductIds //<--this is a list of integers, 
                        // but the new "result" object shows an empty list.
};

Upvotes: 0

Views: 517

Answers (1)

Alexei Levenkov
Alexei Levenkov

Reputation: 100527

It is very unusual to have get and set for one property to work of different sources. You may want to remove set altogether if you always read the value from somewhere else.

Maybe you are looking to override value of the property (i.e. for unit testing) like this:

    [NotMapped]
    public ICollection<int> ProductIds
    {
        get { return _productIds != null ?
             _productIds // return one that was "set"
             : Products.Select(s => s.Id).ToList(); // read from DB
        } 
        set { _productIds = value; }
    }

Upvotes: 3

Related Questions