Kategori: Linq

Temel Linq to Sql Örnekleri

Yeni Kayıt
public static int SaveUser(User user)
{
	using (DbClassesDataContext tmpContext = new DbClassesDataContext())
	{
		tmpContext.Users.InsertOnSubmit(user);
		tmpContext.SubmitChanges();
		return user.ID;
	}
}
 Kayıt Bulma
public static User GetUserByID(int userID)
{
	using (DbClassesDataContext tmpContext = new DbClassesDataContext())
	{
		return (from u in tmpContext.Users
				where u.ID == userID
				select u).SingleOrDefault();
	}
}
 Kayıt Güncelleme
public static int UpdateUser(User user)
{
	using (DbClassesDataContext tmpContext = new DbClassesDataContext())
	{
		User oldUser = GetUserByID(user.ID);
		tmpContext.Users.Attach(user, oldUser);
		tmpContext.SubmitChanges();
		return User.ID;
	}
}

 

Kayıt Silme
public static void DeleteUser(int userID)
{
	using (DbClassesDataContext tmpContext = new DbClassesDataContext())
	{
		var tmpUser = GetUserByID(userID);
		tmpContext.Users.Attach(tmpUser);
		tmpContext.Users.DeleteOnSubmit(tmpUser);
		tmpContext.SubmitChanges();
	}
}

 

Gruplama

query.GroupBy(x => x.ID).Select(g => g.First());