views:

53

answers:

2

i have such code

        var prj = _dataContext.Project.FirstOrDefault(p => p.isPopular == true);
        if (prj != null)
        {
            prj.isPopular = false;
            _dataContext.SaveChanges();
        }


        prj = Details(id);
        prj.isPopular = true;
        _dataContext.SaveChanges();

idea-i have only one record with value true in field isPopular, so i get it and make false, then i get object by id and make it isPopular true. i don't like 2 calls on savechanges. any ideas?

A: 
var prj = _dataContext.Project.FirstOrDefault(p => p.isPopular == true);
    if (prj != null)
    {
        prj.isPopular = false;
    }


    var prj2 = Details(id);
    prj2.isPopular = true;
    _dataContext.SaveChanges();

Of course you should find better variable name for "prj2".

Mattias Jakobsson
A: 
var prj = _dataContext.Project.FirstOrDefault(p => p.isPopular == true || p.id ==id);

prj.Single(p => p.isPpopular == true).IsPopular = false;

prj.Single(p => p.isPpopular == id).IsPopular = true;

_dataContext.SaveChanges();
Rony
Your code will not compile. And if you change "FirstOrDefault()" to "Where()" if will throw exception when there isn't a record with IsPopular == true.
Mattias Jakobsson
I fixed it, we all == once and a while. ;)
jfar
@jfar, That wasn't the issue. Didn't see that.
Mattias Jakobsson
hm... are you sure about call prj.Single()? prj is an object and don't have single method
kusanagi
@user276640, Thats what I meant with my first comment. It will not compile. And you will have to add a null check for the second line as well (and not use Single()).
Mattias Jakobsson