I'm trying to add a new object with nHibernate, but for some reason it tries to update a field on a referenced object that hasn't been provided resulting in:
Cannot insert the value NULL into column 'Value', table 'MyDB.dbo.Type';
column does not allow nulls. UPDATE fails.
Lets assume there's a [Type] table with the record { Id = 1, Value = "Type1" }
I want to add an Item record with code like:
var item = new Item()
{
Name = "New Item",
Type = new Type() { Id = 1 }
}
await _session.SaveAsync(item);
The save status fails presumably because it tries to overwrite the type record { Id = 1, Value = "Type1" } by { Id = 1, Value = null }
The objects are styructured as followed:
public class Type
{
public int Id { get; set }
public string Value { get; set }
}
public class Item
{
public int Id { get; set }
public string Name { get; set }
public Type Type { get; set }
}
And the mapping of them is:
public class TypeMapping : ClassMap<Type>
{
public TypeMapping()
{
Table("[Type]");
Id(x => x.Id).GeneratedBy.Identity();
Map(x => x.Value);
OptimisticLock.Version();
}
}
public class ItemMapping : ClassMap<Item>
{
public ItemMapping()
{
Table("[Item]");
Id(x => x.Id).GeneratedBy.Identity();
Map(x => x.Name);
References(x => x.Type, "TypeId")
.Cascade.None()
.Fetch.Select();
OptimisticLock.Version();
}
}
What do I need to do to make sure it just links the type to the new item instead of trying to overwrite the Type record?