开发者

Linq 2 SQL : update record via a web service

开发者 https://www.devze.com 2023-04-04 00:03 出处:网络
I have a business class. In this business class there are : a context to access database (via .dbml) Some methods

I have a business class. In this business class there are :

  1. a context to access database (via .dbml)
  2. Some methods

A SaveUser(User user) method from this business class is called by a webservice. This method receive the modified User object. How can I update the record in the database by the value from the object receive as parameter (the fields value have the expected values) ?

I tried this :

context.Users.Attach(user); 
context.SubmitChanges();

I tried without the last line, same... no change in the database.

Any idea ?

Thanks,

Update 1

public class RightManager
    {
        private readonly DBDataContext dc;

        public RightManager()
        {
            dc = new DBDataContext();
        }

        public User GetUser(int id)
        {
            User user = dc.GetTable<User>()
                .Where(x => x.Id == id && x.IsEnable == true)
                .SingleOrDefault<User开发者_如何学编程>();

            return user;
        }                     

        public void SaveUser(User user)
        {
            dc.Users.Attach(user);
        }

    }


Sure, the object you recieve by argument is not User object. You have to get one from context (usually by Id), update required properties and submit then.

public void SaveUser (User user) {
    var userToUpdate = context.Users.Where(u => u.Id == user.Id).Single();
    userToUpdate.FirstName = user.FirstName;
    userToUpdate.LastName = user.LastName;

    context.SubmitChanges();
}


You can use one of the overload of the attach method.

See this post: http://blogs.msdn.com/b/dinesh.kulkarni/archive/2007/10/08/attach-if-you-have-something-detached.aspx

0

精彩评论

暂无评论...
验证码 换一张
取 消