无限分级的表,用Linq To Sql操作,该怎么设计类呢!

wxm3630478 2011-08-31 06:00:03
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 用的不顺手啊,都是自己摸,有些实在是摸不出来啊!
*/
...全文
208 15 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
15 条回复
切换为时间正序
请发表友善的回复…
发表回复
wxm3630478 2011-09-01
  • 打赏
  • 举报
回复
[Quote=引用 8 楼 dongxinxi 的回复:]

可以直接在构造函数中写
Childs = new DataContext().Industrys.Where(i=>i.ID == ID).ToList(); 但是这样是实时加载的,效率很低
Linq to sql生成的designer.cs,里面的关联大多都是通过构造构造函数里面,给关联项实例化委托,实现的延迟加载。下面照葫芦画瓢一下简单写一下。虚方法你还可以根据需要自己重写
C# co……
[/Quote]



谢谢提醒,我好像有点眉目啦.........
萧炎 2011-09-01
  • 打赏
  • 举报
回复
用法
-----

//获取数据上下文
private LinqHelper<HrmsDBDataContext> db = new LinqHelper<HrmsDBDataContext>();
/// <summary>
/// 获取所以的录用记录
/// </summary>
/// <returns></returns>
public List<EmployInfo> GetAllEmp()
{
return db.GetList<EmployInfo>();
}
依次类推
萧炎 2011-09-01
  • 打赏
  • 举报
回复
linq吗
我有demo

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
}

需要
using System.Linq.Expressions;

using Models;
  • 打赏
  • 举报
回复
其实质是public class Industry: INotifyPropertyChanging,INotifyPropertyChanged
你的需求只需实现前面一个接口就可以实现了
  • 打赏
  • 举报
回复
public List<Industry> Childs{get;set;}
=>
public EntitySet<Industry> Childs{get;set;}

  • 打赏
  • 举报
回复
可以直接在构造函数中写
Childs = new DataContext().Industrys.Where(i=>i.ID == ID).ToList(); 但是这样是实时加载的,效率很低
Linq to sql生成的designer.cs,里面的关联大多都是通过构造构造函数里面,给关联项实例化委托,实现的延迟加载。下面照葫芦画瓢一下简单写一下。虚方法你还可以根据需要自己重写
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;
}
}
wxm3630478 2011-09-01
  • 打赏
  • 举报
回复
有没有人知道啦


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;}
}
wxm3630478 2011-09-01
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 ssp2009 的回复:]

找点资料
C# code
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;
……
[/Quote]



//谢谢给代码,但是这个不是我想要的...我的要求不只是显示在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 不支持一个表这种关联的功能吧



  • 打赏
  • 举报
回复
有点儿长没细看,感觉那个try有点多余
wxm3630478 2011-09-01
  • 打赏
  • 举报
回复
搞了半天,好像想那个样子啦... ... 但是还是有一些缺陷,求高手改进

Industry表结构:ID Name ParentID IsRoot (无限分级)

贴出源代码:

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
}

  • 打赏
  • 举报
回复
每个结点可以用3-4个属性来定义:
结点编号
名称
父结点编号(根结点可以给个特殊值)
查出根结点下的子结点,然后判断子结点是否还有孙子结点,有就进行递归,并将当前结点添加到集合中

也可以树的形式返回,再加上 List<结点> 子结点的集合
threenewbee 2011-08-31
  • 打赏
  • 举报
回复
我个人觉得关联没有什么意义。

你可以在查询的时候自己连接。
快溜 2011-08-31
  • 打赏
  • 举报
回复
找点资料
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);//递归
}
}
}
}
}


快溜 2011-08-31
  • 打赏
  • 举报
回复
递归?linq不知道如何实现,mark,学习。
wxm3630478 2011-08-31
  • 打赏
  • 举报
回复

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 用的不顺手啊,都是自己摸,有些实在是摸不出来啊!
*/


下班回家! 哎!

111,097

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • AIGC Browser
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧