Update database with LINQ to Entities

主宰稳场 提交于 2019-12-23 01:29:09

问题


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();
}

回答1:


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();
    }



回答2:


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.



来源:https://stackoverflow.com/questions/10474765/update-database-with-linq-to-entities

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!