locked
update data on button click using linq in asp.net Entity Framework RRS feed

  • Question

  • User186310208 posted

    I am trying to do update data...i use linq but cant take 

    FirstOrDefault()

    First()

    protected void BtnUpdate_Click(object sender, EventArgs e)
    {
    using (var context = new WallpaperEntities7())
    {
    var CategoryName = TxtCategoryName.Text;
    var Category = int.Parse(Request["Id"]);


    WallPaperCategory std = (from x in context.WallPaperCategries
    where x.CategoryName == CategoryName
    select x).

    Thursday, August 13, 2020 5:29 AM

Answers

  • User1535942433 posted

    Hi guestadmin@nirvriti.com,

    Accroding to your description,as far as I think,you could update them one-by-one in a Foreach.Then you could call SaveChanges().

    More details,you could refer to below codes:

    WallPaperCategory std = (from x in Context.WallPaperCategries
                            where .... // add where condition here
                            select x).ToList();
    
    foreach (WallPaperCategory x in std )
    {
        x.is_default = false;
    }
    
    Context.SaveChanges();

    More details,you could refer to below article:

    https://stackoverflow.com/questions/20832684/update-records-using-linq

    Best regards,

    Yijing Sun

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, August 14, 2020 3:01 AM

All replies

  • User1120430333 posted

    Linq is a query language that queries any data source that is quarriable such as a database table, array, collection, datatable Linq does not insert, update or delete.

    WallPaperCategory std = (from x in context.WallPaperCategries
    where x.CategoryName == CategoryName
    select x).

    You should be using Single() or SingleOrDefault() to get an object retuned for std. If using SingleOrDefault(), std should checked for null value the default.

    Thursday, August 13, 2020 2:53 PM
  • User1535942433 posted

    Hi guestadmin@nirvriti.com,

    Accroding to your description,as far as I think,you could update them one-by-one in a Foreach.Then you could call SaveChanges().

    More details,you could refer to below codes:

    WallPaperCategory std = (from x in Context.WallPaperCategries
                            where .... // add where condition here
                            select x).ToList();
    
    foreach (WallPaperCategory x in std )
    {
        x.is_default = false;
    }
    
    Context.SaveChanges();

    More details,you could refer to below article:

    https://stackoverflow.com/questions/20832684/update-records-using-linq

    Best regards,

    Yijing Sun

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, August 14, 2020 3:01 AM