在Fluent NHibernate Automap Override中定义唯一列

时间:2011-11-07 21:03:10

标签: nhibernate fluent-nhibernate automapping

我正在尝试使用Fluent NHibernate Automapper Override为实体指定一个唯一的列。对于我的CodeType测试类,我想使Type属性唯一。目标是使用与当前保存的CodeType相同的类型字段创建的“新CodeType()”覆盖在当前实体之上。

我有以下CodeType类:

public class CodeType : SecurableEntity
{

    public virtual string Type { get; set; }
    public virtual string Description { get; set; }

    /// <summary>
    /// This is a placeholder constructor for NHibernate.
    /// A no-argument constructor must be available for NHibernate to create the object.
    /// </summary>
    public CodeType() { }


}

我有以下CodeTypeMap类:

public class CodeTypeMap : IAutoMappingOverride<CodeType>
{
    public void Override(AutoMapping<CodeType> mapping)
    {
        //Doesn't work. Need a way to specify a column as unique.
        mapping.Map(m => m.Type).Unique();
    }
}

通过以下方式将覆盖应用于AutoMap:

    public AutoPersistenceModel Generate()
    {
        var mappings = AutoMap.AssemblyOf<User>(new AutomappingConfiguration());
        mappings.IgnoreBase<Entity>();
        mappings.IgnoreBase<SecurableEntity>();
        mappings.IgnoreBase(typeof(EntityWithTypedId<>));
        mappings.Conventions.Setup(GetConventions());
        mappings.UseOverridesFromAssemblyOf<AutoPersistenceModelGenerator>();
        mappings.UseOverridesFromAssemblyOf<UserMap>();
        mappings.UseOverridesFromAssemblyOf<CodeMap>();
        mappings.UseOverridesFromAssemblyOf<CodeTypeMap>();

        return mappings;
    }

我希望以下代码更新任何“type”等于“existingType”的现有记录。

SecurableEntityRepository<CodeType> ctr = new SecurableEntityRepository<CodeType>();
CodeType ct = new CodeType();
ct.type = "existingType";
ct = ctr.SaveOrUpdate(ct);

如何将NHibernate键从类型字段中删除为唯一?

这可能吗?

1 个答案:

答案 0 :(得分:0)

简短的回答,你想要的是你必须在代码中处理的东西,因为有很多可能性。每次创建新CodeType时,如果已经有一个

,则必须检查数据库
SecurableEntityRepository<CodeType> ctr = new SecurableEntityRepository<CodeType>();
CodeType ct = ctr.GetByType("existingType");
if (ct == null)
{
    ct = new CodeType { type = "existingType" };
}
ctr.SaveOrUpdate(ct);

SecurableEntityRepository<CodeType> ctr = new SecurableEntityRepository<CodeType>();
CodeType ct = ctr.GetByType("existingType");
if (ct != null)
{
    ctr.Detach(ct);
    ctr.Merge(new CodeType{ type = "existingType" });
}

SecurableEntityRepository<CodeType> ctr = new SecurableEntityRepository<CodeType>();
int ctId = ctr.GetIdByType("existingType");
if (ct != 0)
{
    ctr.Merge(new CodeType{ Id = ctId, type = "existingType" });
}

并且有些东西可以用不同的方式写成

    如果您的域名不需要,可以删除
  • public CodeType() { } protected CodeType() { }

  • public AutoPersistenceModel Generate()
    {
        return AutoMap.AssemblyOf<User>(new AutomappingConfiguration())
            .IgnoreBase<Entity>()
            .IgnoreBase<SecurableEntity>()
            .IgnoreBase(typeof(EntityWithTypedId<>))
            .Conventions.Setup(GetConventions())
            .UseOverridesFromAssemblyOf<AutoPersistenceModelGenerator>();
    }