Fast Ado.Net coding

You can do 99% of common sql operations with less code. Most of the operations need only 1-2 lines of code and you get to reuse the object :P .
        string myconnection="";
	using (var conex=new SqlConnection(myconnection))
	{
		conex.Open();
                //inserting a new user into table "users"		
               using (var cmd=conex.CreateInsertQuery("users",new{name="alex"}))
		{
			cmd.ExecuteNonQuery(); //we've inserted alex
					
			//get generated id
			var result=cmd.RecycleCommand("select scope_identity()",null).QuerySingle<int>();
			int generateId= result.Value;

			//get all users with id >1 as IList<User>
			var list=cmd.RecycleCommand("select id,name from users where id>@id",new{id=1}).QueryList<User>();					;
		}
        
        //new parametrized query
	using(var newCmd = conex.CreateCommand("select id,name,age as total from users where age<@age", new {age = 18}))
	{
		var teenagers = newCmd.QueryList<User>();
	}
	}

	var john = new User {Name = "john",Id=1};

	//builds a sql insert statement string from john
	string insert = john.CreateSqlInsert("users");

	//builds update sql statement string , we rename john to george
	string update = new UpdateQueryStringBuilder("users").UpdateFields(new {name = "george"}).Where("id=1").ToString();

Last edited Jan 21, 2011 at 10:59 AM by mike_sapiens, version 8

Comments

No comments yet.