利用attribute实现简单的ORM
我不知道NH的ORM具体如何实现的,我的想法就是通过字段名称和属性名称的对应关系来实现赋值。简单的类型比较好做,直接赋值就可以了。简单类型是说int,string之类的。
有几个需要注意的地方:
1 属性的类型是另外一个类
2 属性是一个集合
3 类有两个属性的类型是同一个类,例如:种子有用量及其单位,和产量及其单位,用量的单位和产量的单位是一个类型
4 属性嵌套,就是属性的这个类型里面的属性还可能是另外一个类
解决办法:
1 用不同的attribute,普通的类型直接赋值,另外一个类的话就交给另外一个类去负责具体的映射
2 分两次映射,然后集合赋值给商品的属性,觉得不是很好,有没有更好的办法呢?
3 添加前缀来区分两个相同类型的不同属性
4 嵌套,一层一层解决
还有就是关于集合,例如:商品的包装规格集合。如何映射呢?是不是需要集合的时候,再次根据商品的ID查询包装规格集合,然后赋值给商品的包装规格属性呢?
那就是两次访问数据库了,我想要一次访问,可以实现吗?
结果集就是下面的格式,第一个table是商品,第二个table是包装规格,循环第一个table映射出来一个商品,但是在映射的时候如果发现属性是List类型,实际上是需要第二个结果集来配合了。如何传第二个的结果集呢?我想不出来。我的解决办法就是一个一个的映射,先映射商品,赋值给一个商品的实例。然后映射包装规格,赋值给一个List,然后把这个List赋值给商品的包装规格属性。
不知道能否在映射商品的同时就映射包装规格集合吗?
数据库的查询结果
http://images.cnblogs.com/cnblogs_com/virusswb/ORM1.JPG
先定义两个attribute,一个用在属性上面,用来映射列
<div class="cnblogs_code">http://images.cnblogs.com/OutliningIndicators/ContractedBlock.gifhttp://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif代码 <!--<br/ /><br/ />Code highlighting produced by Actipro CodeHighlighter (freeware)<br/ />http://www.CodeHighlighter.com/<br/ /><br/ />-->using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BeautyCode.SQLite.ConApp.Common
{
public class ColumnAttribute : Attribute
{
private string _columnType;
/// <summary>
/// 数据库字段类型
/// </summary>
public string ColumnType
{
get { return _columnType; }
set { _columnType = value; }
}
private string _columnName;
/// <summary>
/// 数据库字段名称
/// </summary>
public string ColumnName
{
get { return _columnName; }
set { _columnName = value; }
}
private int _length;
/// <summary>
/// 数据库字段长度
/// </summary>
public int Length
{
get { return _length; }
set { _length = value; }
}
private bool _isIdentity;
/// <summary>
/// 是否标识列
/// </summary>
public bool IsIdentity
{
get { return _isIdentity; }
set { _isIdentity = value; }
}
public ColumnAttribute(string columnName, string columnType, int len, bool isIdentity)
{
this._columnType = columnType;
this._columnName = columnName;
this._length = len;
this._isIdentity = isIdentity;
}
public ColumnAttribute(string columnName)
: this(columnName, string.Empty, 0, false)
{
}
}
}
页:
[1]