Linq实体关系简单概述

本文向大家介绍Linq实体关系,可能好多人还不了解Linq实体关系,没有关系,看完本文你肯定有不少收获,希望本文能教会你更多东西。

Linq实体关系的定义

比如我们的论坛分类表和论坛版块表之间就有关系,这种关系是1对多的关系。也就是说一个论坛分类可能有多个论坛版块,这是很常见的。定义Linq实体关系的优势在于,我们无须显式作连接操作就能处理关系表的条件。

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

  1. [Table(Name = "Categories")]
  2. public class BoardCategory
  3. {
  4. [Column(Name = "CategoryID", DbType = "int identity",
    IsPrimaryKey = true, IsDbGenerated = true, CanBeNull = false)]
  5. public int CategoryID { get; set; }
  6. [Column(Name = "CategoryName", DbType = "varchar(50)", CanBeNull = false)]
  7. public string CategoryName { get; set; }
  8. private EntitySet<Board> _Boards;
  9. [Association(OtherKey = "BoardCategory", Storage = "_Boards")]
  10. public EntitySet<Board> Boards
  11. {
  12. get { return this._Boards; }
  13. set { this._Boards.Assign(value); }
  14. }
  15. public BoardCategory()
  16. {
  17. this._Boards = new EntitySet<Board>();
  18. }
  19. }

CategoryID和CategoryName的映射没有什么不同,只是我们还增加了一个Boards属性,它返回的是Board实体集。通过特性,我们定义了关系外键为BoardCategory(Board表的一个字段)。然后来看看1对多,多端版块表的实体:

  1. [Table(Name = "Boards")]
  2. public class Board
  3. {
  4. [Column(Name = "BoardID", DbType = "int identity", IsPrimaryKey = true,
    IsDbGenerated = true, CanBeNull = false)]
  5. public int BoardID { get; set; }
  6. [Column(Name = "BoardName", DbType = "varchar(50)", CanBeNull = false)]
  7. public string BoardName { get; set; }
  8. [Column(Name = "BoardCategory", DbType = "int", CanBeNull = false)]
  9. public int BoardCategory { get; set; }
  10. private EntityRef<BoardCategory> _Category;
  11. [Association(ThisKey = "BoardCategory", Storage = "_Category")]
  12. public BoardCategory Category
  13. {
  14. get { return this._Category.Entity; }
  15. set
  16. {
  17. this._Category.Entity = value;
  18. value.Boards.Add(this);
  19. }
  20. }
  21. }

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

Linq实体关系的使用

好了,现在我们就可以在查询句法中直接关联表了(数据库中不一定要设置表的外键关系):

    1. Response.Write("-------------查询分类为1的版块-------------<br/>");
    2. var query1 = from b in ctx.Boards where b.Category.CategoryID == 1 select b;
    3. foreach (Board b in query1)
    4. Response.Write(b.BoardID + " " + b.BoardName + "<br/>");
    5. Response.Write("-------------查询版块大于2个的分类-------------<br/>");
    6. var query2 = from c in ctx.BoardCategories where c.Boards.Count > 2 select c;
    7. foreach (BoardCategory c in query2)
    8. Response.Write(c.CategoryID + " " + c.CategoryName + " " + c.Boards.Count + "<br/>");

转载于:https://www.cnblogs.com/Peter-Luo/archive/2012/05/31/2528947.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值