LINQ to SQL, taking the pain out of SQL

I’m not a SQL man.  I never liked it in the slightest.  It always seemed like a ton of work having to create the c# then the SQL duplicating the failure logic.  Just seems like a lot of extra work.

So after you’ve created your database, you can then do all your heavy lifting in LINQ and c#.  Why is this nice?  You’d have to create all the code anyways to get to SQL.  You can still have your stored procedures and views within LINQ to SQL as well.

Here is some sample code for getting a single item back.

public static User Get(string Name)
{
	var user = Context.Users.Single(u => u.Name == Name);

	if(null == user)
		throw new KeyNotFoundException("No user found");

	return user;
}

And for updating / inserting:

public static bool Upsert(string Name, string RfId, string BluetoothId, int Id)
{
	using (var db = new DrunktenderDataContext())
	{
		if (Id > 0)
		{
			var user = db.Users.Single(u => u.UserId == Id);
			user.Name = Name;
			user.RfId = RfId;
			user.BluetoothId = BluetoothId;
		}
		else
		{
			db.Users.InsertOnSubmit(
				new User
					{
						Name = Name,
						RfId = RfId,
						BluetoothId = BluetoothId
					}
				);
		}

		db.SubmitChanges();
	}

	return true;
}

Shawn Jan 20, 2011 @ 4:31 PM

# re: LINQ to SQL, taking the pain out of SQL
To prevent a "Sequence contains no elements" exception you should change your code to
var user = db.Users.SingleOrDefault(u => u.UserId == Id);

www.techdreams.org/.../368-20080925

Post a Comment

Please add 7 and 1 and type the answer here: