商讯信箱
用户名: @
密  码:   注册|忘记密码
登录
个人用户经销商
您的位置:首页 > 技术频道 > 正文

Linq To Sql进阶系列(一)-从映射讲起

作者:Tom Song博客  2008-01-17
【IT168技术文档】
  也可以使用该dbml生成code,命令如下,可以用language选项,控制生成vb.net或c#语言的代码。
  sqlmetal YourDbml.dbml /code: nwind.cs

  在C#3.0入门系列(七)--之OR工具介绍 一文中,我们介绍了OR Designer工具,它生成的就是dbml,可以使用记事本打开DataClasses1.dbml 文件来看。有些属性,是无法从数据库中抽提出来的,比如继承,等。而我们又想对其映射做继承,就需要我们自己手工去修改dbml。好在OR Designer提供这些功能(以后再介绍)。

  关系型数据的映射
  数据间的关系,有2种基本关系。1: 1 和1: M。可以参阅C# 3.0入门系列(二)一文,查阅northwind数据库中的关系图。本文用Order 和Order Detail 表,来阐述其关系的映射。Order 为订单,Order Detail 为订单详情。其关系形式为,一条Order记录对应多条Order Detail 记录。
  你可以在上面产生的code中,找到相应的order类,其中有这么一段
[Table(Name="Orders")] public partial class Order : INotifyPropertyChanging, INotifyPropertyChanged { [Association(Name="Order_OrderDetail", Storage="_OrderDetails", OtherKey="OrderID")] public EntitySet<OrderDetail> OrderDetails { get { return this._OrderDetails; } set { this._OrderDetails.Assign(value); } } }
  在Order类中,有个property,叫OrderDetails,是EntitySet<OrderDetail> 类型的。EntitySet是个集合类型的模板。 其继承关系如下
  EntitySet<TEntity> : IList, ICollection, IList<TEntity>, ICollection<TEntity>, IEnumerable<TEntity>, IEnumerable, IListSource where TEntity : class

  在OrderDetails类中,也可以找到这么一段。
[Table(Name="Order Details")] public partial class OrderDetail : INotifyPropertyChanging, INotifyPropertyChanged { private EntityRef<Order> _Order; [Association(Name="Order_OrderDetail", Storage="_Order", ThisKey="OrderID", IsForeignKey=true)] public Order Order { get { return this._Order.Entity; } set { Order previousValue = this._Order.Entity; if (((previousValue != value) || (this._Order.HasLoadedOrAssignedValue == false))) { this.SendPropertyChanging(); if ((previousValue != null)) { this._Order.Entity = null; previousValue.OrderDetails.Remove(this); } this._Order.Entity = value; if ((value != null)) { value.OrderDetails.Add(this); this._OrderID = value.OrderID; } else { this._OrderID = default(int); } this.SendPropertyChanged("Order"); } } } }
  也就是说Order 在OrderDetail类中,是以EntityRef出现的。这样,在关系双方的各端,我们使用EntityRef和EntitySet来表示其关系。简言之,One在Many端,以EntityRef出现,而Many在One端,以EntitySet出现。上例中,在property 中,因其返回的是this._Order.Entity,直接返回的是Order。
  对于1:1的关系,双双彼此在各自的类中,均以EntityRef出现。大家可以自己试。这样,Order和 OrderDetail
的关系,在各自的类中,都有了体现。体现方式的不同,反映了它们关系主体的不同。
1 2 3
【内容导航】
第1页: 概述 第2页: 第2页
第3页: 第3页
©版权所有。未经许可,不得转载。
[责任编辑:nancy]
[an error occurred while processing this directive]