Skip to content
This repository was archived by the owner on Dec 24, 2022. It is now read-only.

Commit b1a0062

Browse files
committed
Don't populate both Self Ref and FK Ref when referencing same table
1 parent 583ec7a commit b1a0062

File tree

3 files changed

+54
-1
lines changed

3 files changed

+54
-1
lines changed

src/ServiceStack.OrmLite/OrmLiteWriteCommandExtensions.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -844,7 +844,7 @@ internal static void SaveAllReferences<T>(this IDbCommand dbCmd, T instance)
844844

845845
if (result != null)
846846
{
847-
if (refField != null)
847+
if (refField != null && refSelf == null)
848848
refField.SetValueFn(result, pkValue);
849849

850850
dbCmd.CreateTypedApi(refType).Save(result);
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
using System.Linq;
2+
using NUnit.Framework;
3+
using ServiceStack.DataAnnotations;
4+
5+
namespace ServiceStack.OrmLite.Tests.Issues
6+
{
7+
public class PareInfo
8+
{
9+
[AutoIncrement]
10+
public int Id { get; set; }
11+
public string name { get; set; }
12+
public int? PareInfoId { get; set; }
13+
[Reference]
14+
public PareInfo Pare { get; set; }
15+
}
16+
17+
public class LoadReferencesFKandSelfRefIssue
18+
: OrmLiteTestBase
19+
{
20+
[Test]
21+
public void Does_not_populate_both_FK_and_self_reference()
22+
{
23+
using (var db = OpenDbConnection())
24+
{
25+
db.DropAndCreateTable<PareInfo>();
26+
27+
var p1 = new PareInfo { name = "p1" };
28+
var p2 = new PareInfo
29+
{
30+
name = "p2",
31+
};
32+
p1.Pare = p2;
33+
34+
db.Save(p1, references: true);
35+
36+
var p1AndRefs = db.LoadSingleById<PareInfo>(p1.Id);
37+
Assert.That(p1AndRefs.Pare, Is.Not.Null);
38+
Assert.That(p1AndRefs.PareInfoId, Is.EqualTo(p2.Id));
39+
40+
var p2AndRefs = db.LoadSingleById<PareInfo>(p2.Id);
41+
Assert.That(p2AndRefs.Pare, Is.Null);
42+
Assert.That(p2AndRefs.PareInfoId, Is.Null);
43+
44+
var rows = db.Select<PareInfo>().OrderBy(x => x.Id).ToList();
45+
Assert.That(rows[0].name, Is.EqualTo("p1"));
46+
Assert.That(rows[0].PareInfoId, Is.EqualTo(p2.Id));
47+
Assert.That(rows[1].name, Is.EqualTo("p2"));
48+
Assert.That(rows[1].PareInfoId, Is.Null);
49+
}
50+
}
51+
}
52+
}

tests/ServiceStack.OrmLite.Tests/ServiceStack.OrmLite.Tests.csproj

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -132,6 +132,7 @@
132132
<Compile Include="Issues\CanBuildExpressionWithAbstractType.cs" />
133133
<Compile Include="Issues\ColumnGuessingTests.cs" />
134134
<Compile Include="Issues\JoinBoolSqlServerIssue.cs" />
135+
<Compile Include="Issues\LoadReferencesFKandSelfRefIssue.cs" />
135136
<Compile Include="Issues\MergingNestedSqlExpressionIssue.cs" />
136137
<Compile Include="Issues\SqlExpressionSubSqlExpressionIssue.cs" />
137138
<Compile Include="Legacy\ApiSqliteLegacyTests.cs" />

0 commit comments

Comments
 (0)