Home > Blockchain >  Cannot insert the value NULL into on referenced object
Cannot insert the value NULL into on referenced object

Time:03-12

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?

CodePudding user response:

A colleague of mine became available and he gave me a quick solution to my problem.

var item = new Item()
{
    Name = "New Item",
    Type = Session.Load<Type>(1)
}
await _session.SaveAsync(item);

Apparently that Load command doesn't actually load anything as long as you don't use any properties on the "loaded" object. That way it's linking to the referenced reccord, just as I wanted.

CodePudding user response:

when you're trying to make a Type you only put in one parameter for:

Id {get, set}
Value {get, set}

so it'll fill the string one with NULL if you want it to have the string as "Type1" you should do instead:

    Type = new Type() { Id = 1 , Value = "Type1"}
  • Related