Skip to content

Fix querying with delayed entity insert #2416

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 6 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
121 changes: 121 additions & 0 deletions src/NHibernate.Test/Async/NHSpecificTest/GH2414/Fixture.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by AsyncGenerator.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------


using System;
using System.Linq;
using NHibernate.Cfg.MappingSchema;
using NHibernate.Mapping.ByCode;
using NUnit.Framework;
using NHibernate.Linq;

namespace NHibernate.Test.NHSpecificTest.GH2414
{
using System.Threading.Tasks;
/// <summary>
/// Fixture using 'by code' mappings
/// </summary>
/// <remarks>
/// This fixture is identical to <see cref="FixtureAsync" /> except the <see cref="Entity" /> mapping is performed
/// by code in the GetMappings method, and does not require the <c>Mappings.hbm.xml</c> file. Use this approach
/// if you prefer.
/// </remarks>
[TestFixture]
public class FixtureAsync : TestCaseMappingByCode
{
protected override HbmMapping GetMappings()
{
var mapper = new ModelMapper();
mapper.Class<Entity>(rc =>
{
rc.Id(x => x.Id, m => m.Generator(Generators.Identity));
rc.Property(x => x.Name);
});
mapper.Class<EntityWithGuidKey>(rc =>
{
rc.Id(x => x.Id, m => m.Generator(Generators.Guid));
rc.Property(x => x.Name);
});

return mapper.CompileMappingForAllExplicitlyAddedEntities();
}

protected override void OnSetUp()
{
using (var session = OpenSession())
using (var transaction = session.BeginTransaction())
{
var e1 = new Entity { Name = "Bob" };
session.Save(e1);

var e2 = new Entity { Name = "Sally" };
session.Save(e2);

var e3 = new EntityWithGuidKey() { Id = Guid.NewGuid(), Name = "Bob" };
session.Save(e3);

var e4 = new EntityWithGuidKey() { Id = Guid.NewGuid(), Name = "Sally" };

transaction.Commit();
}
}

protected override void OnTearDown()
{
using (var session = OpenSession())
using (var transaction = session.BeginTransaction())
{
// The HQL delete does all the job inside the database without loading the entities, but it does
// not handle delete order for avoiding violating constraints if any. Use
// session.Delete("from System.Object");
// instead if in need of having NHbernate ordering the deletes, but this will cause
// loading the entities in the session.
session.CreateQuery("delete from System.Object").ExecuteUpdate();

transaction.Commit();
}
}

[Test]
public async Task QueryWithEqualDelayedPostInsertIdentifierInWhereAsync()
{
using (var session = OpenSession())
{
var entity = new Entity() { Name = "NewEntity" };
await (session.PersistAsync(entity));
var result = await (session.Query<Entity>().Where(x => x == entity).ToListAsync());
Assert.That(result, Has.Count.EqualTo(0));
}
}

[Test]
public async Task QueryWithEqualDelayedPostInsertIdentifierInWhereWithGuidKeyEntityAsync()
{
using (var session = OpenSession())
{
var entity = new EntityWithGuidKey() { Name = "NewEntity" };
await (session.PersistAsync(entity));
var result = await (session.Query<EntityWithGuidKey>().Where(x => x == entity).ToListAsync());
Assert.That(result, Has.Count.EqualTo(0));
}
}

[Test]
public async Task QueryWithNotEqualDelayedPostInsertIdentifierInWhereAsync()
{
using (var session = OpenSession())
{
var entity = new Entity() { Name = "NewEntity" };
await (session.PersistAsync(entity));
var result = await (session.Query<Entity>().Where(x => x != entity).ToListAsync());
Assert.That(result, Has.Count.EqualTo(2));
}
}
}
}
10 changes: 10 additions & 0 deletions src/NHibernate.Test/NHSpecificTest/GH2414/Entity.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
using System;

namespace NHibernate.Test.NHSpecificTest.GH2414
{
class Entity
{
public virtual int Id { get; set; }
public virtual string Name { get; set; }
}
}
14 changes: 14 additions & 0 deletions src/NHibernate.Test/NHSpecificTest/GH2414/EntityWithGuidKey.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NHibernate.Test.NHSpecificTest.GH2414
{
class EntityWithGuidKey
{
public virtual Guid Id { get; set; }
public virtual string Name { get; set; }
}
}
109 changes: 109 additions & 0 deletions src/NHibernate.Test/NHSpecificTest/GH2414/Fixture.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
using System;
using System.Linq;
using NHibernate.Cfg.MappingSchema;
using NHibernate.Mapping.ByCode;
using NUnit.Framework;

namespace NHibernate.Test.NHSpecificTest.GH2414
{
/// <summary>
/// Fixture using 'by code' mappings
/// </summary>
/// <remarks>
/// This fixture is identical to <see cref="Fixture" /> except the <see cref="Entity" /> mapping is performed
/// by code in the GetMappings method, and does not require the <c>Mappings.hbm.xml</c> file. Use this approach
/// if you prefer.
/// </remarks>
[TestFixture]
public class Fixture : TestCaseMappingByCode
{
protected override HbmMapping GetMappings()
{
var mapper = new ModelMapper();
mapper.Class<Entity>(rc =>
{
rc.Id(x => x.Id, m => m.Generator(Generators.Identity));
rc.Property(x => x.Name);
});
mapper.Class<EntityWithGuidKey>(rc =>
{
rc.Id(x => x.Id, m => m.Generator(Generators.Guid));
rc.Property(x => x.Name);
});

return mapper.CompileMappingForAllExplicitlyAddedEntities();
}

protected override void OnSetUp()
{
using (var session = OpenSession())
using (var transaction = session.BeginTransaction())
{
var e1 = new Entity { Name = "Bob" };
session.Save(e1);

var e2 = new Entity { Name = "Sally" };
session.Save(e2);

var e3 = new EntityWithGuidKey() { Id = Guid.NewGuid(), Name = "Bob" };
session.Save(e3);

var e4 = new EntityWithGuidKey() { Id = Guid.NewGuid(), Name = "Sally" };

transaction.Commit();
}
}

protected override void OnTearDown()
{
using (var session = OpenSession())
using (var transaction = session.BeginTransaction())
{
// The HQL delete does all the job inside the database without loading the entities, but it does
// not handle delete order for avoiding violating constraints if any. Use
// session.Delete("from System.Object");
// instead if in need of having NHbernate ordering the deletes, but this will cause
// loading the entities in the session.
session.CreateQuery("delete from System.Object").ExecuteUpdate();

transaction.Commit();
}
}

[Test]
public void QueryWithEqualDelayedPostInsertIdentifierInWhere()
{
using (var session = OpenSession())
{
var entity = new Entity() { Name = "NewEntity" };
session.Persist(entity);
var result = session.Query<Entity>().Where(x => x == entity).ToList();
Assert.That(result, Has.Count.EqualTo(0));
}
}

[Test]
public void QueryWithEqualDelayedPostInsertIdentifierInWhereWithGuidKeyEntity()
{
using (var session = OpenSession())
{
var entity = new EntityWithGuidKey() { Name = "NewEntity" };
session.Persist(entity);
var result = session.Query<EntityWithGuidKey>().Where(x => x == entity).ToList();
Assert.That(result, Has.Count.EqualTo(0));
}
}

[Test]
public void QueryWithNotEqualDelayedPostInsertIdentifierInWhere()
{
using (var session = OpenSession())
{
var entity = new Entity() { Name = "NewEntity" };
session.Persist(entity);
var result = session.Query<Entity>().Where(x => x != entity).ToList();
Assert.That(result, Has.Count.EqualTo(2));
}
}
}
}
1 change: 1 addition & 0 deletions src/NHibernate/Async/Type/NullableType.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@

using System;
using System.Data.Common;
using NHibernate.Action;
using NHibernate.Engine;
using NHibernate.SqlTypes;
using NHibernate.Util;
Expand Down
10 changes: 10 additions & 0 deletions src/NHibernate/Type/NullableType.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System;
using System.Data.Common;
using NHibernate.Action;
using NHibernate.Engine;
using NHibernate.SqlTypes;
using NHibernate.Util;
Expand Down Expand Up @@ -152,6 +153,15 @@ public sealed override void NullSafeSet(DbCommand st, object value, int index, I
// I definitely need to look into this more...
st.Parameters[index].Value = DBNull.Value;
}
else if (value is DelayedPostInsertIdentifier)
{
if (IsDebugEnabled)
{
Log.Debug("binding 0 to parameter: {0}", index);
}

st.Parameters[index].Value = 0;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This assumes the identifier is compatible with an int, and this assumes 0 is not a valid value for it. This will be wrong in many cases.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

DelayedPostInsertIdentifier exists only for auto-increment fields, so I believe that the value 0 in this case is correct

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I compared this behavior with entity framework core 3 comparison by reference for an entity that is not yet stored in the table returns exactly parameter 0 in all cases

Copy link
Member

@bahusoid bahusoid Jun 15, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What if entity.Id is not 0 for transient entity and for instance it's -1?

DelayedPostInsertIdentifier exists only for auto-increment fields, so I believe that the value 0 in this case is correct

Not true for the following SQL Server table:

CREATE TABLE Entity
(  
Id int IDENTITY(0,1), -- start from 0
Name varchar (20) 
 );  

}
else
{
if (IsDebugEnabled)
Expand Down