linq to sql中外键关联关系

其实使用linq to sql使用设计器比较容易操作外键关联的表。我这里也只是说说代码上的重点。可以方便以后手写

还是sqlserver2000中的northwind库。打开linq to sql classes设计器。吧customers表和order表拖到表区域。发现这两个表有个链接那就是外键关联的。

看设计器中的代码。customer类中

。。。

 private string _Phone;
 
 private string _Fax;
 
 private EntitySet<Order> _Orders;

。。。

在这些字段属性有个 private EntitySet<Order> _Orders;他对应的就是order表类集合

和数据库建立特性链接的时候

[Association(Name="Customer_Order", Storage="_Orders", OtherKey="CustomerID")]
 public EntitySet<Order> Orders
 {
  get
  {
   return this._Orders;
  }
  set
  {
   this._Orders.Assign(value);
  }
 }

然后还有就是customer的构造函数中

public Customer()
 {
  OnCreated();
  this._Orders = new EntitySet<Order>(new Action<Order>(this.attach_Orders), new Action<Order>(this.detach_Orders));
 }

在看orders实体类

他的私有字段是这个:private EntityRef<Customer> _Customer;

属性是:[Association(Name="Customer_Order", Storage="_Customer", ThisKey="CustomerID", IsForeignKey=true)]
 public Customer Customer
 {
  get
  {
   return this._Customer.Entity;
  }
  set
  {
   Customer previousValue = this._Customer.Entity;
   if (((previousValue != value)
      || (this._Customer.HasLoadedOrAssignedValue == false)))
   {
    this.SendPropertyChanging();
    if ((previousValue != null))
    {
     this._Customer.Entity = null;
     previousValue.Orders.Remove(this);
    }
    this._Customer.Entity = value;
    if ((value != null))
    {
     value.Orders.Add(this);
     this._CustomerID = value.CustomerID;
    }
    else
    {
     this._CustomerID = default(string);
    }
    this.SendPropertyChanged("Customer");
   }
  }
 }

他的构造函数是这个

public Order()
 {
  OnCreated();
  this._Customer = default(EntityRef<Customer>);
 }

代码也没什么说的。有两个类EntitySet 和 EntityRef。一个是集合一个是引用。

本文使用Blog_Backup未注册版本导出,请到soft.pt42.com注册。

转载于:https://www.cnblogs.com/zjypp/archive/2007/08/17/2319488.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值