- SQL Injection Proof.
- Intellisense
- Compile check when database changes
- Faster development
- Auto-generated domain objects that are usable small projects
STEP 1:
- Open Visual Studio 2008 File-->New-->ASP.NET WEBApplication.
- Give name as "Forum_Linq to SQL".
- Goto Solution Explorer and right click on "Forum_Linq to SQL".
- Ensure your project target framework as Dotnet Farmework 3.5, cause L2S works only on 3.5 framework. For this right click the "Forum_Ling to SQL" Goto Properties change Target Framework as 3.5.
Now connect your Database in server explorer and drag and drop the tables to DataClasses1.dbml file. It will automatically converted into a class. See the image below.
Now we will see how to retrive data from this forum_user class. For this first we will create the object for the datacontext. Datacontext means it point to the dbml file which is created by us. In this project the datacontext name as "Dataclasses1DataContext". See the code below
using System;using System.Collections.Generic; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Linq; namespace Forum_Linq_to_SQL {
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
GridView gv = new GridView();
DataClasses1DataContext obj = new DataClasses1DataContext();
var user = (from c in obj.Forum_Users select c).ToList();
gv.DataSource = gv;
gv.DataBind();
}
}
}
How to Insert the new record into the Forum_user class?
DataClasses1DataContext obj = new DataClasses1DataContext();
Forum_User user = new Forum_User();
user.UserId = "xxxxx";
user.Pwd = "xxxx";
obj.Forum_Users.InsertOnSubmit(user);
obj.SubmitChanges();
How to Edit the record into the Forum_user class?
DataClasses1DataContext obj = new DataClasses1DataContext();
var user = (from c in obj.Forum_Users where c.UserId=="xxxxx" select c).First();
user.Pwd = "zzzz";
obj.SubmitChanges();
How to Delete the record into the Forum_user class?
DataClasses1DataContext obj = new DataClasses1DataContext();
var user = (from c in obj.Forum_Users where c.UserId == "xxxxx" select c).Single();
obj.Forum_Users.DeleteOnSubmit(user);
obj.SubmitChanges();
How to Join two tables?
DataClasses1DataContext obj = new DataClasses1DataContext();
var user = (from c in obj.Forum_Users join s in obj.Forum_UsersTwo on s.UserId equals c.UserId select new {c.UserId,s.username}).First();
0 comments:
Post a Comment