Add a unique restriction on multiple columns to a foreign key using automated automatic start

I am a novice NHibernate and fluent-nhibernate. And I have some problems with the unique restriction and display of nhibernate.

I have the following part of a domain model.

public class Batch
{
    public virtual int Id {get; set;}
    public virtual string Name {get; set;}
    public virtual IList<BatchParameter> BatchParameters {get; set;}
}
public class BatchParameter
{
    public virtual int Id {get; set;}
    public virtual string Name {get; set;}
    public virtual Batch Batch {get; set;}
}

I am trying to use fluent-nhibernate to map it to db (SQLServer) using autopilot. I want to configure my db to have:

  • Primary Keys for Id Properties

  • Foreign key in BatchParamets table

  • Unique constant in the Batch table in the Name column

  • Unique constant in the BatchParameters table in the Name and Batch_Id columns

So, I wrote this code:

public class BatchMapping : IAutoMappingOverride<Batch>
{
    public void Override(FluentNHibernate.Automapping.AutoMapping<Batch> mapping)
    {
        mapping.Id( b => b.Id);
        mapping.HasMany<BatchParameter>(p => p.BatchParameters).Cascade.All().Inverse();
    }
}

public class BatchParameterMapping : IAutoMappingOverride<BatchParameter>
{
    public void Override(FluentNHibernate.Automapping.AutoMapping<BatchParameter> mapping)
    {
        mapping.Id( b => b.Id);
        mapping.Map(b => b.Name).Unique();
        //mapping.Map(p => p.Name).UniqueKey("Batch_Parameter");
        //mapping.Map(p => p.Batch.Id).UniqueKey("Batch_Parameter");
    }
}

No problem for primary keys, foreign key and first unique constraint. A bit of a headache for a unique limitation.

- ?

!

+3
2

-, , : ...Map(b => b.Name)... BatchMapping, BatchParameterMapping.

public class BatchMapping : IAutoMappingOverride<Batch>
{
    public void Override(AutoMapping<Batch> mapping)
    {
        mapping.Map(b => b.Name).Unique();
    }
}

, BatchParameter.Batch - BatchParameter Batch, References(...) Map(...). References Map .

public class BatchParameterMapping : IAutoMappingOverride<BatchParameter>
{
    public void Override(AutoMapping<BatchParameter> mapping)
    {
        mapping.Map(p => p.Name).UniqueKey("Batch_Parameter");
        mapping.References(p => p.Batch).UniqueKey("Batch_Parameter");
    }
}

, Id Batch.BatchParameters. NHibernate . Override , - , , .

+1

Id Name BatchParameter, . , Batch BatchParameter, Reference. , :

public class BatchParameterMapping : IAutoMappingOverride<BatchParameter>
{
    public void Override(FluentNHibernate.Automapping.AutoMapping<BatchParameter> mapping)
    {
        mapping.CompositeId()
            .KeyProperty(x => x.Id)
            .KeyProperty(x => x.Name);

        mapping.References(x => x.Batch);
    }
}
0

Source: https://habr.com/ru/post/1728269/


All Articles