Thursday, February 17, 2011

LINQ to SQL

To add Linq
make sure you have a connection to the database in the Server Explorer
Right click on the project in the Solution Explorer and select New ITem
In the new Item list select LINQ to SQL
It will open a new Designer window
Drag the classes you want to use from the Server explorer onto the Design window



Here is the code for inserting person

protected void Button1_Click(object sender, EventArgs e)
{


Person peeps = new Person();
peeps.FirstName = txtFirstName.Text;
peeps.LastName = txtLastName.Text;
dc.Persons.InsertOnSubmit(peeps);
try
{

dc.SubmitChanges();

//Session["mypeep"] = peeps;
// Response redirect
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}

Here is the query for filling the data grid

public partial class _Default : System.Web.UI.Page
{

peopleDataContext dc = new peopleDataContext();

protected void Page_Load(object sender, EventArgs e)
{
var contacts = from p in dc.PersonContacts
where p.ContactTypeKey == 6
orderby p.Person.LastName
select new { p.Person.LastName, p.Person.FirstName, p.ContactInfo };
GridView1.DataSource=contacts.ToList();
GridView1.DataBind();

}

Here is the linq code for the insert of the magazine

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Default3 : System.Web.UI.Page
{
mySubscription s;
protected void Page_Load(object sender, EventArgs e)
{
s = (mySubscription)Session["magOrder"];
txtFirstName.Text = s.Firstname;
txtLastName.Text = s.Lastname;
txtAddress.Text = s.Address;
txtCity.Text = s.City;
txtState.Text = s.State;
txtZip.Text = s.Zip;
txtPhone.Text = s.Phone;
txtMagazine.Text = s.Magazine;
txtLength.Text = s.Subscriptiontype;
}
protected void Button1_click(object sender, EventArgs e)
{
magazineClassesDataContext dc = new magazineClassesDataContext();
Customer cust = new Customer();
cust.CustLastName = txtLastName.Text;
cust.CustFirstName = txtFirstName.Text;
cust.CustAddress = txtAddress.Text;
cust.CustCity = txtCity.Text;
cust.CustState = txtState.Text;
cust.CustZipcode = txtZip.Text;
cust.CustPhone = txtPhone.Text;

dc.Customers.InsertOnSubmit(cust);



Subscription subs = new Subscription();
subs.Customer = cust;
subs.MagDetID = s.MagdetailID;
subs.SubscriptionStart = DateTime.Now;
subs.SubscriptionEnd = null;

dc.Subscriptions.InsertOnSubmit(subs);

dc.SubmitChanges();

Response.Redirect("Default4.aspx?msg=Thank you for your subscription");
}
}

I will post the complete magazineSubscription project soom

No comments:

Post a Comment