设计是否可以更合理一点?——关于ORM中业务实体的讨论

今天看到David Hayden写的Castle ActiveRecord - Active Record Pattern Built on NHibernate - Rapid Application Development文章,其中他的实体类设计如下:

[ActiveRecord("Posts")]

public class Article : ActiveRecordBase<Post>
{
    
private int _id;

    [PrimaryKey(PrimaryKeyType.Native, 
"PostId")]
    
public int Id
    
{
        
getreturn _id;}

        
set{ _id = value;}
    }


    
private int _blogId;

    [Property]
    
public int BlogId
    
{
        
getreturn _blogId;}

        
set{ _blogId = value;}
    }


    
private int _categoryId;

    [Property]
    
public int CategoryId
    
{
        
getreturn _categoryId;}

        
set{ _categoryId = value;}
    }


    
private string _title = string.Empty;

    [Property]
    
public string Title
    
{
        
getreturn _title;}

        
set{ _title = value;}
    }


    
private string _description = string.Empty;

    [Property]
    
public string Description
    
{
        
getreturn _description;}

        
set{ _description = value;}
    }

}

注意到出现了下面这样的两个属性:

public int BlogId

public int CategoryId

在这个业务实体中,对于Article对象来说,更直观的应该说它属于哪一个Blog,哪一个Category,而不是指定一个整型的值,这种用ID的设计其实是把把数据库结构带入到了业务实体中。我们知道引入ORM,使得我们可以用面向对象的思维来考虑实体间的关系,如果继续使用ID来解决,引入ORM的作用可能就大打折扣了,因此,是否把实体类修改为如下这样更合理一些呢?

[ActiveRecord("Posts")]

public class Article : ActiveRecordBase<Post>
{
    
private int _id;

    [PrimaryKey(PrimaryKeyType.Native, 
"PostId")]
    
public int Id
    
{
        
getreturn _id;}

        
set{ _id = value;}
    }


    
private Blog _blog;

    [Property]
    
public Blog Blog
    
{
        
getreturn _blog;}

        
set{ _blog = value;}
    }


    
private Category _category;

    [Property]
    
public Category Category
    
{
        
getreturn _category;}

        
set{ _category = value;}
    }


    
private string _title = string.Empty;

    [Property]
    
public string Title
    
{
        
getreturn _title;}

        
set{ _title = value;}
    }


    
private string _description = string.Empty;

    [Property]
    
public string Description
    
{
        
getreturn _description;}

        
set{ _description = value;}
    }

}

即用这里的两个属性来代替整型的ID

public Category Category

public Blog Blog

估计也有很多朋友会这样去用,下午跟一个朋友讨论时,他说修改前加载Article对象时,加载的仅仅是2个ID,而修改后却要加载Blog,Category对象所有的属性,是否存在性能上的下降?欢迎大家就这个问题说出你的看法。

(出处:http://terrylee.cnblogs.com

posted @ 2006-06-19 17:59  TerryLee  阅读(6105)  评论(40编辑  收藏  举报