0

I Have a table in my databse that one of the columns named NumOfView shows the number of clicks on a link. That link shows some info from a row in this table. I used onclick event in anchor tag like this:

[email protected]("NumOfClicks", "AdvertiseHelper",new { id = Model.id[i] })

In NumOfClicks function I used this code

 public void NumOfClicks (int id)
    {
        Ad ad1 = new Ad();
        var advert = (from ad in storedb.Ads where ad.AdId == id select     ad.NumOfView).First();
        advert += 1;

    }

advert

is the amount of

NumOfView

in table that I want to increase it 1 unit. but I don't know how to continue coding for update this value in table. Can anybody help me please?

1 Answer 1

3

This is the basics of how it should be done. First you have to select the record itself from the database rather than the number of clicks. Increment the number of clicks on that record, then submit the changes to the DataContext.

public void IncrementClickCount(int id)
{
    var advert = 
        (from ad in storedb.Ads 
         where ad.AdId == id
         select ad).Single();   // Select the row in the database represented by "ad"
    advert.NumOfView++;         // Perform the increment on the column

    // SubmitChanges is how an update is done in Linq2Sql 
    // This requires a .dbml file for the database object file
    // storedb.SubmitChanges();    // Assumes storedb is a valid DataContext, updates

    // SaveChanges is how an update is done in EntityFramework
    // It is recognizable because it uses an .edmx file for its database object
    storedb.SaveChanges();
}

This was similarly asked in SO question: Entity Framework - Update a row in a table

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

4 Comments

I can't see SubmitChanges method but I see AcceptAllChanges and thought it's simillar to SubmitChanges method and use it but doesn't work...
@Tena your storedb looks to be an ObjectContext. In order to update a database, you'll need it to be a DataContext. If you're not using a database here, I would need to know more about how you have your data structure situated.
Thank for your answer and your time. I used this link for my project. link the The approach I used is similar to that.
@Tena: Ok, it looks like your sample is using EntityFramework instead of Linq 2 Sql (a subtle difference but it matters). I'll post an update with the method that should be appropriate and a link to an SO article that is similar.

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.