流畅的NHibernate映射

时间:2010-12-15 17:16:24

标签: c# .net fluent-nhibernate nhibernate-mapping

我有这些课程:

public class Entity
{
  public virtual Guid Id { get; set; }
  public virtual string EntityName { get; set; }
  public virtual IDictionary<string, Property> { get; set; }
  // ...
}

public class Property
{
  public virtual int? IntValue { get; set; }
  public virtual decimal? DecimalValue { get; set; }
}

是否可以创建Fluent NHibernate映射,以便执行生成的模式将为这些表提供:

[Entities]
* Id : UNIQUEIDENTIFIER NOT NULL
* EntityName : NVARCHAR(50) NOT NULL
with a clustered index on "Id"

[Properties]
* EntityId : UNIQUEIDENTIFIER NOT NULL
* PropertyName : VARCHAR(50) NOT NULL
* IntValue : INT NULL
* DecimalValue : DECIMAL(12,6) NULL
with a clustered index on "EntityId" and "PropertyName"

或者我需要更改课程吗?

答案比“是/否”更详细,将非常感激:)

2 个答案:

答案 0 :(得分:1)

除了您需要手动创建的聚集索引之外,是的。您是否绝对需要FNH来生成架构?

为什么不直接根据您的要求生成架构,然后相应地映射它。

(未经过测试或其他任何内容,写在我的头顶)

public class EntityMap : ClassMap<Entity>
{
    public EntityMap()
    {
        Table("Entities");

        Id(x => x.Id).GeneratedBy.GuidComb();
        Map(x => x.Name).CustomSqlType("NVARCHAR").Length(50).Not.Nullable();
        HasMany<Property>(x => x.Properties)
            .Table("Properties")
            .KeyColumn("PropertyName")
            .Inverse()
            .AsBag();
    }
}

public class PropertyMap : ClassMap<Property>
{
    public PropertyMap()
    {
        Table("Properties");

        Id(x => x.Id).GeneratedBy.GuidComb();
        Map(x => x.PropertyName).Length(50).Not.Nullable();
        Map(x => x.IntValue);
        Map(x => x.DecimalValue);
    }
}

答案 1 :(得分:0)

这是我提出的映射:

public sealed class EntityMap : ClassMap<Entity>
{
    public EntityMap()
    {
        Table("Entities");

        Id(c => c.Id);
        Map(c => c.EntityName).CustomSqlType("nvarchar(50)").Not.Nullable();

        HasMany(c => c.Properties)
            .KeyColumn("EntityId")
            .AsMap<string>("PropertyName")
            .Component(part =>
            {
                part.Map(x => x.IntValue);
                part.Map(x => x.DecimalValue).Precision(12).Scale(6);
            });
    }
}

模式生成产生了这个:

create table Entities (
   Id UNIQUEIDENTIFIER not null,
   EntityName nvarchar(50) not null,
   primary key (Id)
)

create table Properties (
   EntityId UNIQUEIDENTIFIER not null,
   IntValue INT null,
   DecimalValue DECIMAL(12, 6) null,
   PropertyName INT not null,
   primary key (EntityId, PropertyName)
)

alter table Properties 
    add constraint FK63646D8550C14DC4 
    foreign key (EntityId) 
    references Entities

这几乎是我需要的,除了列顺序(次要问题)和PropertyName是nvarchar(255)而不是varchar(50)(我实际关心的事情)。