开发者

When the connection to database starts if i use DataContext?

public class GetFromDatabase
{
    ExaminatorDataContext dataContext;

    public GetFromDatabase()
    {
        dataContext = new ExaminatorDataContext();
    }
 public void UpdateUserName(string login, string firstName, string lastName, string middleName)
    {
        var user = this.dataContext.Users.Where(u => u.Login == login).SingleOrDefault();
        user.FirstName = firstName;
        user.LastName = lastName;
        user.MiddleN开发者_StackOverflow中文版ame = middleName;
        this.dataContext.SubmitChanges();
    }
public string GetUserRole(string login)
    {

        return (from user in this.dataContext.Users
                join role in this.dataContext.Roles on user.RoleId equals role.RoleId
                where user.Login == login
                select role.RoleName).SingleOrDefault();
}

When connection stars and closes when I call these functions? And one more question. Should I use 'using'?


In Linq to SQL, the connection opens and closes each time you query the table object:

var user = this.dataContext.Users.Where(u => u.Login == login).SingleOrDefault();

And opens and closes when you do an update:

this.dataContext.SubmitChanges();

You don't need to use 'using' since LINQ to SQL will manage the connection.

From http://www.west-wind.com/weblog/posts/246222.aspx :

Keep in mind too that DataContext and Connections aren't tied 1 to 1. Connections will only be open while you iterate over data (or if you explicitly use the Connection provided with a Command or streaming to a DataReader()). Once you reach the end of a list connections close automatically.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜