Skip to content

Instantly share code, notes, and snippets.

@chilversc
Created January 25, 2010 14:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chilversc/285899 to your computer and use it in GitHub Desktop.
Save chilversc/285899 to your computer and use it in GitHub Desktop.
NHibernate one-to-one problem
-- statement #1
begin transaction with isolation level: Unspecified
-- statement #2
SELECT bar_.Foo,
bar_.Rate as Rate1_,
bar_.Value as Value1_
FROM [Bar] bar_
WHERE bar_.Foo = '2b76e14d-c48e-490d-9d1c-9d0900ee14ec' /* @p0 */
-- statement #3
INSERT INTO [Bar]
(Rate,
Value,
Foo)
VALUES (5 /* @p0 */,
10 /* @p1 */,
'2b76e14d-c48e-490d-9d1c-9d0900ee14ec' /* @p2 */)
-- statement #4
ERROR:
Could not execute command: INSERT INTO [Bar] (Rate, Value, Foo) VALUES (@p0, @p1, @p2)
-- statement #5
WARN:
System.Data.SqlClient.SqlException: The INSERT statement conflicted with the FOREIGN KEY constraint "FK52E419EEE5E038AA". The conflict occurred in database "sandbox", table "dbo.Foo", column 'Id'.
The statement has been terminated.
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection)
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj)
at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj)
at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)
at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result)
at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(DbAsyncResult result, String methodName, Boolean sendToPipe)
at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
at NHibernate.AdoNet.AbstractBatcher.ExecuteNonQuery(IDbCommand cmd)
at NHibernate.AdoNet.NonBatchingBatcher.AddToBatch(IExpectation expectation)
at NHibernate.Persister.Entity.AbstractEntityPersister.Insert(Object id, Object[] fields, Boolean[] notNull, Int32 j, SqlCommandInfo sql, Object obj, ISessionImplementor session)
-- statement #6
ERROR:
The INSERT statement conflicted with the FOREIGN KEY constraint "FK52E419EEE5E038AA". The conflict occurred in database "sandbox", table "dbo.Foo", column 'Id'.
The statement has been terminated.
-- statement #7
ERROR:
Could not synchronize database state with session
using System;
using System.IO;
using System.Threading;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using FluentNHibernate.Mapping;
using NHibernate.Tool.hbm2ddl;
namespace ValueMapping
{
public class Program
{
private static void Main(string[] args)
{
HibernatingRhinos.Profiler.Appender.NHibernate.NHibernateProfiler.Initialize();
if (Directory.Exists("schema"))
Directory.Delete("schema", true);
Directory.CreateDirectory("schema");
var cfg =
Fluently.Configure()
.Database(
MsSqlConfiguration.MsSql2005
.ConnectionString(x => x.Server(".").Database("sandbox").TrustedConnection())
.ProxyFactoryFactory<NHibernate.ByteCode.LinFu.ProxyFactoryFactory>()
)
.Mappings(x =>
x.FluentMappings
.Add<FooMapping>()
.Add<BarMapping>()
.ExportTo("schema"))
.BuildConfiguration();
new SchemaExport(cfg).Drop(false, true);
new SchemaExport(cfg).Execute(false, true, false);
var sf = cfg.BuildSessionFactory();
object id;
try
{
using (var session = sf.OpenSession())
using (var t = session.BeginTransaction())
{
var f = new Foo();
f.Name = "bob";
f.Bar = new Bar();
f.Bar.Foo = f;
f.Bar.Rate = 5;
f.Bar.Value = 10;
id = session.Save(f);
t.Commit();
}
}
finally
{
HibernatingRhinos.Profiler.Appender.NHibernate.NHibernateProfiler.Stop();
Thread.Sleep(1000);
}
}
}
public class Foo
{
public virtual Guid Id { get; set; }
public virtual string Name { get; set; }
public virtual Bar Bar { get; set; }
public virtual bool Equals(Foo other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
return other.Id.Equals(Id);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != typeof (Foo)) return false;
return Equals((Foo) obj);
}
public override int GetHashCode()
{
return Id.GetHashCode();
}
}
public class Bar
{
public virtual Foo Foo { get; set; }
public virtual int Value { get; set; }
public virtual int Rate { get; set; }
public virtual bool Equals(Bar other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
return Equals(other.Foo, Foo);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != typeof (Bar)) return false;
return Equals((Bar) obj);
}
public override int GetHashCode()
{
return Foo.GetHashCode();
}
}
public sealed class FooMapping : ClassMap<Foo>
{
public FooMapping()
{
Id(x => x.Id).GeneratedBy.GuidComb();
Map(x => x.Name);
HasOne(x => x.Bar).Constrained().Cascade.All().ForeignKey("none");
}
}
public sealed class BarMapping : ClassMap<Bar>
{
public BarMapping()
{
CompositeId().KeyReference(x => x.Foo);
//Id<Guid>("id").GeneratedBy.Foreign("Foo");
//HasOne(x => x.Foo).Constrained().ForeignKey();
Map(x => x.Rate);
Map(x => x.Value);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment