Skip to content

Commit 3843108

Browse files
author
Marc Sallin
committed
#27: Added UniqueAttribute.
1 parent 4f06cfd commit 3843108

File tree

4 files changed

+41
-0
lines changed

4 files changed

+41
-0
lines changed
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
namespace SQLite.CodeFirst
2+
{
3+
/// <summary>
4+
/// The action to resolve a UNIQUE constraint violation.
5+
/// Is used together with the <see cref="UniqueAttribute"/>.
6+
/// </summary>
7+
public enum OnConflictAction
8+
{
9+
None,
10+
Rollback,
11+
Abort,
12+
Fail,
13+
Ignore,
14+
Replace
15+
}
16+
}
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
using System;
2+
3+
namespace SQLite.CodeFirst
4+
{
5+
/// <summary>
6+
/// The UNIQUE Constraint prevents two records from having identical values in a particular column.
7+
/// </summary>
8+
[AttributeUsage(AttributeTargets.Property)]
9+
public sealed class UniqueAttribute : Attribute
10+
{
11+
public UniqueAttribute(OnConflictAction onConflict = OnConflictAction.None)
12+
{
13+
OnConflict = onConflict;
14+
}
15+
16+
public OnConflictAction OnConflict { get; set; }
17+
}
18+
}

SQLite.CodeFirst/DbInitializers/SqliteInitializerBase.cs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
using System.Data.Entity.ModelConfiguration.Conventions;
44
using SQLite.CodeFirst.Convention;
55
using System.IO;
6+
using System.Linq;
67
using SQLite.CodeFirst.Utility;
78

89
namespace SQLite.CodeFirst
@@ -36,6 +37,10 @@ protected SqliteInitializerBase(DbModelBuilder modelBuilder)
3637
// See https://github.com/msallin/SQLiteCodeFirst/issues/7 for details.
3738
modelBuilder.Conventions.Remove<TimestampAttributeConvention>();
3839

40+
modelBuilder.Properties()
41+
.Having(x => x.GetCustomAttributes(false).OfType<UniqueAttribute>().FirstOrDefault())
42+
.Configure((config, attribute) => config.HasColumnAnnotation("IsUnique", attribute));
43+
3944
// By default there is a 'ForeignKeyIndexConvention' but it can be removed.
4045
// And there is no "Contains" and no way to enumerate the ConventionsCollection.
4146
// So a try/catch will do the job.

SQLite.CodeFirst/SQLite.CodeFirst.csproj

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,8 @@
8383
<Compile Include="..\Shared\AssemblySharedInfo.cs">
8484
<Link>Properties\AssemblySharedInfo.cs</Link>
8585
</Compile>
86+
<Compile Include="Attributes\OnConflictAction.cs" />
87+
<Compile Include="Attributes\UniqueAttribute.cs" />
8688
<Compile Include="Entities\IHistory.cs" />
8789
<Compile Include="Internal\Builder\NameCreators\IndexNameCreator.cs" />
8890
<Compile Include="Internal\Builder\NameCreators\SpecialChars.cs" />

0 commit comments

Comments
 (0)