Tuesday, March 1, 2011

More LINQ Examples

This linq code writes a new magazine with one magazine detail to the database. Remember you must add a new LINQ to SQL object to the web site and then drag the appropriate tables onto the LINQ designer in order for this work

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

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

magazineClassesDataContext dc = new magazineClassesDataContext();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
var stype = from s in dc.SubscriptionTypes
select new { s.SubscriptTypeID, s.SubscriptTypeName };

DropDownList1.DataSource = stype.ToList();
DropDownList1.DataTextField = "SubscriptTypeName";
DropDownList1.DataValueField = "SubscriptTypeID";
DropDownList1.DataBind();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
Magazine mag = new Magazine();
mag.MagName = txtMagName.Text;
mag.MagType = txtMagType.Text;
dc.Magazines.InsertOnSubmit(mag);

MagazineDetail magdet = new MagazineDetail();
magdet.Magazine = mag;
magdet.SubscriptTypeID = int.Parse(DropDownList1.SelectedValue.ToString());
magdet.SubscriptionPrice = decimal.Parse(txtPrice.Text.ToString());

dc.MagazineDetails.InsertOnSubmit(magdet);

dc.SubmitChanges();



}
}

No comments:

Post a Comment