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/p/2319488.html