HasMany is not a null foreign key

I have two classes ( simplified for example):

public class Data
{
    public int Id {get; set;}
    public string Value { get; set; }
}
public class DataContainer
{
    public int Id {get; set;}
    public IList<Data> DataPoints { get; set; }
}

Basically, the DataContainer class contains a data set ( and other properties are not shown ). The Data class does not know about the DataContainer, but it cannot exist outside of one. For this, I use HasMany relationships.

I map the DataContainer as follows:

Id(x => x.Id);
HasMany<Data>(x => x.DataPoints)
    .Not.KeyNullable()
    .Cascade.All();

And the created SQL for Data looks like this:

create table [Data] (
   [Id] INT IDENTITY NOT NULL,
   [DataContainer] INT null,
   primary key ([Id])
)
alter table [Data] 
    add constraint FK173EC9226585807B 
    foreign key ([DataContainer]) 
    references [DataContainer]

The problem is that I do not want [DataContainer] INT null, instead I want it to not allow nulls

[DataContainer] INT not null

I thought. KeyNullable () would do this, but it does not seem to work.

Thank.

+3
source share
2 answers

, , hbm.xml, Fluent, , , . ( "-null" "" ):

<bag cascade="all" name="Items" mutable="true">
  <key foreign-key="FK_MyEntity2_MyEntity1" not-null="true">
    <column name="MyEntity1_Id" />
  </key>
  <one-to-many class="MyNs.MyEntity2, MyAssembly, Version=0.4.700.0, Culture=neutral, PublicKeyToken=null" />
</bag>

, NHibernate, Fluent. 6.4 NHibernate (3.0.0, , 2.1.2)

. <key> NOT NULL, NHibernate . , ( ), inverse = "true". . .

, , NHibernate "-" DDL , ( , ) NULL.

+2

, ( Yhrn), , Constrained(). ForeignKey():

Data:

 this.HasOne(x => x.DataContainer).Cascade.All().Constrained().ForeignKey();

SQL - NULL, :

ALTER TABLE [dbo].[Data]  WITH CHECK ADD  CONSTRAINT [FK_DataToDataContainer] FOREIGN KEY([Id])
REFERENCES [dbo].[DataContainer] ([Id])
GO

ALTER TABLE [dbo].[Data] CHECK CONSTRAINT [FK_DataToDataContainer]
GO
0

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


All Articles