步步学LINQ to SQL:将类映射到数据库表

发表于:2011-11-21 09:55

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:罗江华    来源:51Testing软件测试网采编

分享:

  相对于数据库列名,如果你想为字段或属性设置成不同的名字,可以使用(Name="")标签来实现.否则程序会默认以你的字段或属性名称作为列名,正如我们这里的Book's主键:Id那样。

[Column( IsPrimaryKey = true, IsDbGenerated = true )]
public int Id { get; set; }

  (3)使用[Column]特性为表添加其他非关系列

  后面部分我们将会回到关系对象上来。现在,咱们开始了解表对象的非主键,外键列。Book有两个这样的列:Title 和 Price。其数据类型由数据库的money类型转换到了.NET的decimal类型,以及由varchars类型转换到了.NET的string类型。LINQ会自动为你处理这些数据类型之间的转换。

[Column] public string Title { get; set; }
[Column] public decimal Price { get; set; }

  Book Catalog应用程序的Author和Category也进行了这样的处理,即这三个类对象都对应于自己的数据表:

using System.Data.Linq.Mapping;
namespace LINQDemo
{
[Table( Name = "Books" )]
public class Book
{
[Column( IsPrimaryKey = true, IsDbGenerated = true )] public int Id { get; set; }
[Column] public string Title { get; set; }
[Column] public decimal Price { get; set; }
}
[Table (Name="Authors")]
public class Author
{
[Column (IsPrimaryKey = true, IsDbGenerated = true )] public int Id { get; set; }
[Column] public string Name { get; set; }
}
[Table (Name="BookCategories")]
public class Category
{
[Column (IsPrimaryKey = true, IsDbGenerated = true )] public int Id { get; set; }
[Column] public string Name { get; set; }
}
}

33/3<123
100家互联网大公司java笔试题汇总,填问卷领取~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号