zoukankan      html  css  js  c++  java
  • Linq to sql(八):继承与关系(四)

    实体关系的定义 比如我们的论坛分类表和论坛版块表之间就有关系,这种关系是1对多的关系。

    也就是说一个论坛分类可能有多个论坛版块,

    这是很常见的。定义实体关系的优势在于,我们无须显式作连接操作就能处理关系表的条件。

           首先来看看分类表的定义:

     

    [Table(Name = "Categories")]

    public class BoardCategory

    {

        [Column(Name = "CategoryID", DbType = "int identity", IsPrimaryKey = true, IsDbGenerated = true, CanBeNull = false)]

        public int CategoryID { get; set; }

     

        [Column(Name = "CategoryName", DbType = "varchar(50)", CanBeNull = false)]

        public string CategoryName { get; set; }

     

        private EntitySet<Board> _Boards;

     

        [Association(OtherKey = "BoardCategory", Storage = "_Boards")]

        public EntitySet<Board> Boards

        {

            get { return this._Boards; }

            set { this._Boards.Assign(value); }

        }

     

        public BoardCategory()

        {

            this._Boards = new EntitySet<Board>();

        }

    }

           CategoryIDCategoryName的映射没有什么不同,只是我们还增加了一个Boards属性,

    它返回的是Board实体集。通过特性,我们定义了关系外键为BoardCategoryBoard表的一个字段)。

    然后来看看1对多,多端版块表的实体:

     

    [Table(Name = "Boards")]

    public class Board

    {

        [Column(Name = "BoardID", DbType = "int identity", IsPrimaryKey = true, IsDbGenerated = true, CanBeNull = false)]

        public int BoardID { get; set; }

     

        [Column(Name = "BoardName", DbType = "varchar(50)", CanBeNull = false)]

        public string BoardName { get; set; }

     

        [Column(Name = "BoardCategory", DbType = "int", CanBeNull = false)]

        public int BoardCategory { get; set; }

     

        private EntityRef<BoardCategory> _Category;

     

        [Association(ThisKey = "BoardCategory", Storage = "_Category")]

        public BoardCategory Category

        {

            get { return this._Category.Entity; }

            set

            {

                this._Category.Entity = value;

                value.Boards.Add(this);

            }

    }

    }

           在这里我们需要关联分类,设置了Category属性使用BoardCategory字段和分类表关联。

  • 相关阅读:
    数据库连接池Druid使用总结
    Mysql中查看每个IP的连接数
    解Bug之路-Druid的Bug
    python 安装python-memcached and pylibmc两个模块
    memcache
    python 交互式执行SQL
    tomcat内存泄漏存入dump文件
    MySQL SQL优化之覆盖索引
    【 Tomcat 】tomcat8.0 基本参数调优配置
    配置路由器/交换机的Telnet登录
  • 原文地址:https://www.cnblogs.com/kevin2013/p/1749042.html
Copyright © 2011-2022 走看看