111,097
社区成员




//获取数据上下文
private LinqHelper<HrmsDBDataContext> db = new LinqHelper<HrmsDBDataContext>();
/// <summary>
/// 获取所以的录用记录
/// </summary>
/// <returns></returns>
public List<EmployInfo> GetAllEmp()
{
return db.GetList<EmployInfo>();
}
依次类推
public class LinqHelper<TDataContext> where TDataContext:DataContext,new()
{
TDataContext db = null;
private readonly string connStr = "Data Source=MICROSOF-AFFEB9\\SQLEXPRESS;Initial Catalog=HRMSDB;Integrated Security=True";
/// <summary>
/// 获取上下文数据
/// </summary>
/// <returns></returns>
public TDataContext GetContext()
{
db = new TDataContext();
db.Connection.ConnectionString = connStr;
db.DeferredLoadingEnabled = IsAtOnceLoad.IsDload == false;
return db;
}
#region 查询
/// <summary>
/// 获取全部数据
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public List<T> GetList<T>() where T : class
{
var db = GetContext();
return db.GetTable<T>().ToList();
}
/// <summary>
/// 根据条件获取数据
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="predicate"></param>
/// <returns></returns>
public List<T> GetList<T>(Expression<Func<T, bool>> predicate) where T : class
{
var db = GetContext();
return db.GetTable<T>().Where(predicate).ToList();
}
/// <summary>
/// 根据条件获取单个数据
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="predicate"></param>
/// <returns></returns>
public T GetEntity<T>(Expression<Func<T, bool>> predicate) where T : class
{
if (db == null)
{
db = GetContext();
}
return db.GetTable<T>().Where(predicate).FirstOrDefault();
}
#endregion
#region 添加
/// <summary>
/// 插入数据
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="Entity"></param>
public void Insert<T>(T Entity) where T : class
{
try
{
var db = GetContext();
db.GetTable<T>().InsertOnSubmit(Entity);
db.SubmitChanges(ConflictMode.ContinueOnConflict);
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
#endregion
#region 删除
/// <summary>
/// 根据条件删除数据
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="predicate"></param>
public void Delete<T>(Expression<Func<T, bool>> predicate) where T : class
{
try
{
var db = GetContext();
var obj = db.GetTable<T>().Where(predicate).FirstOrDefault();
db.GetTable<T>().DeleteOnSubmit(obj);
db.SubmitChanges(ConflictMode.ContinueOnConflict);
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
#endregion
#region 修改
/// <summary>
/// 更改数据
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="Entity"></param>
public void Update<T>(T Entity) where T : class
{
try
{
db.SubmitChanges(ConflictMode.ContinueOnConflict);
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
#endregion
}
public class Industry
{
private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs(String.Empty);
public event PropertyChangingEventHandler PropertyChanging;
partial void OnCreated();
public Industry()
{
//
// Summary:
// Initializes a new instance of the System.Data.Linq.EntitySet<TEntity> class
// while supplying handlers for add and remove operations.
//
// Parameters:
// onAdd:
// Delegate for System.Data.Linq.EntitySet<TEntity>.Add(TEntity).
//
// onRemove:
// Delegate for System.Data.Linq.EntitySet<TEntity>.Remove(TEntity).
this._Items = new EntitySet<Industry>(new Action<Industry>(this.attach_Industrys), new Action<Industry>(this.detach_Industrys));
OnCreated();
}
public string ID{get;set;}
public string Name{get;set;}
//该怎么写关联 [global::System.Data.Linq.Mapping.AssociationAttribute()]
public Industry Parent{get;set;}
//该怎么写关联
public List<Industry> Childs{get;set;}
protected virtual void SendPropertyChanging()
{
if ((this.PropertyChanging != null))
{
this.PropertyChanging(this, emptyChangingEventArgs);
}
}
private void attach_Industrys(Industry entity)
{
this.SendPropertyChanging();
entity.Parent = this;
}
private void detach_Industrys(Industry entity)
{
this.SendPropertyChanging();
entity.Parent = null;
}
}
Linq To Sql 如何实现这样一个Industry类:
public class Industry
{
public string ID{get;set;}
public string Name{get;set;}
// 关键是如何关联
//该怎么写关联 [global::System.Data.Linq.Mapping.AssociationAttribute()]
public Industry Parent{get;set;}
//该怎么写关联
public EntitySet<Industry> Childs{get;set;}
}
//谢谢给代码,但是这个不是我想要的...我的要求不只是显示在treeview
//我要返回的就是一个Industry对象
DataClasses1DataContext dc= new DataClasses1DataContext();
Industry industry = dc.Industry.SingleOrDefault(d => d.ID.Equals("001")) // 给他一个ID,返回一个Industry
industry.Parent.Name //能够获取到他的父行业
industry.Childs //能够获取到他的子行业
//用Linq to sql 的应该知道,延时加载,关键是属性[Parent,Childs]不知道怎么关联,当调用到Parent和Childs时候,自动去查询数据库,而不要重新写代码判断.
//估计Linq to Sql 不支持一个表这种关联的功能吧
public partial class TestIndustryDataContext : System.Data.Linq.DataContext
{
public System.Data.Linq.Table<Industry2> Industry2
{
get
{
return this.GetTable<Industry2>();
}
}
//略.........................
}
//---------------------------------------------------------------------------------------------------
[global::System.Data.Linq.Mapping.TableAttribute(Name="dbo.Industry2")]
public partial class Industry2
{
private string _ID;
private string _Name;
private string _ParentID;
private bool _IsRoot;
public Industry2()
{
OnCreated();
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_ID", DbType="NVarChar(50)",IsPrimaryKey=true)]
public string ID
{
get
{
return this._ID;
}
set
{
if ((this._ID != value))
{
this._ID = value;
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Name", DbType="NVarChar(50)")]
public string Name
{
get
{
return this._Name;
}
set
{
if ((this._Name != value))
{
this._Name = value;
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_ParentID", DbType="NVarChar(50)")]
private string ParentID
{
get
{
return this._ParentID;
}
set
{
if ((this._ParentID != value))
{
this._ParentID = value;
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_IsRoot", DbType="Bit NOT NULL")]
public bool IsRoot
{
get
{
return this._IsRoot;
}
set
{
if ((this._IsRoot != value))
{
this._IsRoot = value;
}
}
}
}
//----------------------------------------------------------------------------------------------------
partial class Industry2 : INotifyPropertyChanging, INotifyPropertyChanged
{
private EntityRef<Industry2> _Parent;
private EntitySet<Industry2> _Childs;
private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs(String.Empty);
void OnCreated()
{
this._Childs = new EntitySet<Industry2>(new Action<Industry2>(this.attach_Industry2), new Action<Industry2>(this.detach_Industry2));
this._Parent = new EntityRef<Industry2>();
}
public Industry2 Parent
{
get
{
Industry2 entity = this._Parent.Entity;
bool hasload = this._Parent.HasLoadedOrAssignedValue;
if (entity == null || !hasload)
{
try
{
//我这里是 get的时候去查询
//这个地方有什么好办法处理吗? 求?
using (TestIndustryDataContext dc = new TestIndustryDataContext())
{
_Parent.Entity = dc.Industry2.SingleOrDefault(industry => industry.ID.Equals(_ParentID));
}
}
catch (Exception ex) { throw ex; }
}
return _Parent.Entity;
}
set
{
Industry2 previousValue = this._Parent.Entity;
if ((previousValue != value) || !this._Parent.HasLoadedOrAssignedValue)
{
this.SendPropertyChanging();
if (previousValue != null)
{
this._Parent.Entity = null;
previousValue.Childs.Remove(this);
}
this._Parent.Entity = value;
if ((value != null))
{
//此对象添加到父行业的子行业集合中
value.Childs.Add(this);
this._ParentID = value._ID;
}
else
{
this._ParentID = String.Empty;
}
this.SendPropertyChanged("Parent");
}
}
}
public EntitySet<Industry2> Childs
{
get
{
if (_Childs == null)
{
_Childs = new EntitySet<Industry2>();
}
if (!_Childs.HasLoadedOrAssignedValues)
{
try
{
using (TestIndustryDataContext dc = new TestIndustryDataContext())
{
var v = dc.Industry2.Where(d => d.ParentID.Equals(_ID));
_Childs.Assign(v);
}
}
catch(Exception ex)
{
throw ex;
}
}
return _Childs;
}
set
{
this._Childs.Assign(value);
}
}
#region 接口事件
public event PropertyChangingEventHandler PropertyChanging;
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void SendPropertyChanging()
{
if ((this.PropertyChanging != null))
{
this.PropertyChanging(this, emptyChangingEventArgs);
}
}
protected virtual void SendPropertyChanged(String propertyName)
{
if ((this.PropertyChanged != null))
{
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
#endregion
#region 当Childs添加一个对象和移除一个对象时
private void attach_Industry2(Industry2 entity)
{
this.SendPropertyChanging();
entity.Parent = this;
}
private void detach_Industry2(Industry2 entity)
{
this.SendPropertyChanging();
entity.Parent = null;
}
#endregion
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
DataClasses1DataContext dataContext = new DataClasses1DataContext();
public Form1()
{
InitializeComponent();
addTree(0, (TreeNode)null);
treeView1.ExpandAll();
}
public void addTree(int parentID, TreeNode pNode)
{
IQueryable<tree> query = from q in dataContext.tree where q.parentid == parentID select q;
foreach (var g in query)
{
TreeNode treeNode = new TreeNode();
if (pNode == null)
{
treeNode.Text = g.nodeid.ToString();
treeNode.Name = g.nodeid.ToString();
treeView1.Nodes.Add(treeNode);
addTree(Int32.Parse(g.nodeid.ToString()), treeNode);//递归
}
else
{
treeNode.Text = g.nodeid.ToString();
treeNode.Name = g.nodeid.ToString();
pNode.Nodes.Add(treeNode);
addTree(Int32.Parse(g.nodeid.ToString()), treeNode);//递归
}
}
}
}
}
Industry表 无限分级
//表结构: ID Name ParentID IsRoot
//如果用类表示如下:
public class Industry
{
public string ID{get;set;}
public string Name{get;set;}
// 关键是如何关联
//该怎么写关联 [global::System.Data.Linq.Mapping.AssociationAttribute()]
public Industry Parent{get;set;}
//该怎么写关联
public EntitySet<Industry> Childs{get;set;}
}
/*
Linq to sql 该怎么做?
还是Linq to sql 不能这么做? 还是有什么其他的办法?
求教...!
Linq to sql 没用过.........都是用ado.net............Linq to sql 用的不顺手啊,都是自己摸,有些实在是摸不出来啊!
*/