Susan
Susan

Reputation: 1832

Update database with LINQ to Entities

I've been doing some research on how to update an existing record using LINQ, but I'm not having any luck. This is the method I've created - intellisense does not like the db.SubmitChanges().

public void updateRestaurant(int RestID, int HoursID, string Web, string Desc)
{
    RestaurantsEntities db = new RestaurantsEntities();
    RESTAURANT restDetails = (from RESTAURANT in db.RESTAURANTs
                                    where RESTAURANT.REST_ID == RestID
                                    select RESTAURANT).Single();
    restDetails.HOURS_ID = HoursID;
    restDetails.REST_WEBSITE = Web;
    restDetails.REST_DESC = Desc;

    db.SubmitChanges();
}

Upvotes: 2

Views: 11741

Answers (2)

MrJD
MrJD

Reputation: 1889

Your creating an instance of an object in your link graph.

This is incorrect. You need to create an instance of your object context, it starts with the file name of your linq graph and ends in DataContext. Eg if your link file is called myDb then your context name is myDbDataContext.

RestaurantsEntities db = new RestaurantsEntities();
RESTAURANT restDetails = db.RESTAURANTs.single(c=>c.REST_ID == RestID);
restDetails.HOURS_ID = HoursID;
restDetails.REST_WEBSITE = Web;
restDetails.REST_DESC = Desc;
db.SubmitChanges();

this is assuming an object in your context is called RESTAURANT.

You are required to use the context so that the context can manage what you want to insert, update and delete and at the same time maintain relationships. You are unable to create instances of objects and then apply them to your context. They must be created via context.

In reply to comment and update:
I am just not thinking straight. I've updated my code but its not going to help. I'm fairly sure your doing everything correctly

Have a look at this question and this post

UPDATE
I think its your query thats giving you trouble. It's disconnected from your context. Try the linq code i provided above.

Upvotes: 0

Prashanth Thurairatnam
Prashanth Thurairatnam

Reputation: 4361

Try using db.SaveChanges();

    public void updateRestaurant(int RestID, int HoursID, string Web, string Desc)
    {
        RestaurantsEntities db = new RestaurantsEntities();
        RESTAURANT restDetails = (from RESTAURANT in db.RESTAURANTs
                                        where RESTAURANT.REST_ID == RestID
                                        select RESTAURANT).Single();
        restDetails.HOURS_ID = HoursID;
        restDetails.REST_WEBSITE = Web;
        restDetails.REST_DESC = Desc;
        db.SaveChanges();
    }

Upvotes: 4

Related Questions