NHibernate的复合键VS复合唯一约束 [英] NHibernate Composite Key vs Composite Unique Constraint

查看:305
本文介绍了NHibernate的复合键VS复合唯一约束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用NHibernate的,如果我有,有一个独特的约束,它们可以唯一地由约束条件确定的实体,就是它不如重新present约束作为组合键或有一个单独的编号字段,有复合唯一约束?我一直在读,它被认为是坏使用组合键与NHibernate的,如果它可以帮助,并与传统的数据库时,才应使用。

When using NHibernate, if I have an entity that has a unique constraint and that can be identified uniquely by that constraint, is it better to represent the constraint as a composite key or have a seperate Id field and have a composite unique constraint? I have been reading that it is considered "bad" to use composite keys with NHibernate if it can helped and should only be used when working with legacy databases.

图片设置如下:

class Book
{
   public virtual int Id { get; protected set; }
   public virtual string Author { get; set; }
   public virtual IList<BookEdition> Editions { get; set; } //HasMany (one to many)
}

class BookEdition
{
   public virtual string Title { get; set; }
   public virtual string Language { get; set; }
   public virtual int Edition { get; set; }
}

下面我们就针对地方对语言版本约束的BookEdition约束,即不能有这本书在同一种语言的两个版本。任何版本也可以唯一地确定了一个版本号和一个语言

Here we have a constraint for the BookEdition where it has a constraint on the Language and Edition, i.e. there can't be two editions of the book in the same language. Any edition can also be uniquely identified by an edition number and a language.

哪种方法被认为是更好的NHibernate的?使用语言/版作为组合标识或引入一个id变量为BookEdition并有复合唯一约束呢?

Which approach is considered better in NHibernate? Use the Language/Edition as a composite Id or introduce an Id variable for the BookEdition and have a composite unique constraint instead?

推荐答案

Surrorgate键(附加ID变量)一般不仅NHibernate的更好。自然键(在这里:语言版)的问题是,他们有一个企业的意思。业务需求的发展在时间,你肯定要改变你的自然键在未来,这可能是非常痛苦的。另外你的SQL连接与那里的条件将更加复杂。

Surrorgate key (additional Id variable) is better in general not only in NHibernate. The problem with natural keys (here: Language and Edition) is that they have a "business" meaning. Business needs evolve in time and you will certainly have to change your natural keys in the future, which could be very painful. Additionally your SQL joins and where conditions will be more complicated.

这可能是BookEdition的FNH映射与复合唯一约束:

This could be FNH mapping of BookEdition with composite unique constraint:

    Id(x => x.Id);
    Map(x => x.Title);
    Map(x => x.Language).UniqueKey("MyCompositeUniqueConstraint");
    Map(x => x.Edition).UniqueKey("MyCompositeUniqueConstraint");

顺便说一句。这是很好的做法,不显示surrorgate键值客户。他们往往一些企业的意义分配给他们,然后他们想改变他们还有:)

Btw. it is good practice to not show surrorgate key values to customers. They tend to assign some business meaning to them and then they want to change them as well:).

这篇关于NHibernate的复合键VS复合唯一约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆