简体   繁体   English

C#-流利的NHibernate映射问题

[英]C# - Fluent NHibernate mapping question

Is there a way to avoid the explicit Id mapping in Fluent NHibernate ? 有没有一种方法可以避免Fluent NHibernate中的显式Id映射?

I want it to somehow generate the entry id automatically so that I wouldn't have to introduce it as a part of the class. 我希望它以某种方式自动生成条目ID,这样我就不必在班级中介绍它。

public class HeyMapping
{
    public String Name { get; set; }
    public DateTime Timestamp { get; set; }
}

public class HeyMapping : ClassMap<HeyMapping>
{
    public HeyMapping()
    {
        Not.LazyLoad();

        // I'm not particularly sure how this line works, but
        // it fails the mapping unit test.
        CompositeId().KeyProperty(x => x.Name);

        Map(x => x.Name).Not.Nullable().Length(64);
        Map(x => x.Timestamp).Not.Nullable();
    }
}

If you want to have no id in your entity, you still have to map an Id so NHibernate knows the database column to use. 如果您想在实体中没有ID ,则仍然必须映射一个ID,以便NHibernate知道要使用的数据库列。

You can call 你可以打电话

Id<TColumnDataType>("column_name");

Please note that you will give up some NHibernate functionality (specifically cascading updates and the ability to call SaveOrUpdate() ) and incur a performance penalty on the database side for having database-only identity (I believe NHibernate will have to make extra queries for comparison). 请注意,您将放弃一些NHibernate功能(特别是级联更新和调用SaveOrUpdate()的能力),并且由于拥有仅数据库身份而在数据库方面造成性能损失(我相信NHibernate将不得不进行额外的查询以进行比较) )。

I usually concede this point and allow the Id as the one persistence concern in my domain classes, so I would do this: 我通常承认这一点,并允许将Id作为我的域类中的一个持久性关注点,因此我可以这样做:

public class HeyMapping
{
    protected internal int Id { get; set; } // persistence concern

    public virtual String Name { get; set; }
    public virtual DateTime Timestamp { get; set; }
}

I realize you might not want to do this; 我知道您可能不想这样做; I'm just letting you know that there is a tradeoff. 我只是想告诉您,这是一个折衷方案。

创建一个基类,所有映射的实体都将从该基类继承,然后将Id属性添加到基类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM