Linq入门实例

 1.数据定义

using System;
using System.Collections.Generic;
using System.Web;
using System.Linq;
using System.Data.Linq;
using System.Data.Linq.Mapping;

namespace QuickStart
{
    [Table]
    public class Cat
    {
       
        private int catId;

        private string name;
        private char sex;
        private float weight;

        public Cat()
        {
        }
        [Column(IsDbGenerated=true,AutoSync=AutoSync.OnInsert,IsPrimaryKey = true)]       

        public virtual int CatId
        {
            get { return catId; }
            set { catId = value; }
        }
        [Column] 
        public virtual string Name
        {
            get { return name; }
            set { name = value; }
        }
        [Column] 
        public virtual char Sex
        {
            get { return sex; }
            set { sex = value; }
        }
        [Column] 
        public virtual float Weight
        {
            get { return weight; }
            set { weight = value; }
        }

    }
}

 2.数据访问

string conn = "Server=(local);initial catalog=Test;uid=sa;pwd=abc123_";
protected void Page_Load(object sender, EventArgs e)
{
  DataContext db = new DataContext(conn);
  Table<Cat> catTable = db.GetTable<Cat>();
   Cat c1 = catTable.Where(t => t.CatId == 3).FirstOrDefault();
  Response.Write(c1.Name);       

}

删除,修改,查询

 public DataSet GetAll()
{
  DataSet ds = new DataSet();
  DataContext db = new DataContext(conn);
  Table<Cat> catTable = db.GetTable<Cat>();
    string sql = "select * from cat";
  SqlDataAdapter adapter = new SqlDataAdapter(sql,conn);
  adapter.Fill(ds);
  return ds;
}

public int DeleteCat(int CatId)
{
  DataContext db = new DataContext(conn);
  Table<Cat> catTable = db.GetTable<Cat>();
  Cat c1 = catTable.Where(t => t.CatId == CatId).FirstOrDefault();
  catTable.DeleteOnSubmit(c1);
  db.SubmitChanges();
  return 1;
}

public int UpdateCat(int CatId,string Name,char Sex,float Weight,int CustomerId)
{
  DataContext db = new DataContext(conn);
  Table<Cat> catTable = db.GetTable<Cat>();
  Cat c1 = catTable.Where(t => t.CatId == CatId).FirstOrDefault();
  c1.Name = Name;
  c1.Sex = Sex;
  c1.Weight = Weight;
  db.SubmitChanges();
  return 1;

}

原文地址:https://www.cnblogs.com/kenny999/p/2300357.html