Skip to content
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

Description column (#33) #35

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
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
3 changes: 2 additions & 1 deletion EfEnumToLookup/EfEnumToLookup.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -47,13 +47,14 @@
<Reference Include="System" />
<Reference Include="System.ComponentModel.DataAnnotations" />
<Reference Include="System.Core" />
<Reference Include="System.Data.Entity" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="LookupGenerator\ContextExtensions.cs" />
<Compile Include="LookupGenerator\EnumGeneratorException.cs" />
<Compile Include="LookupGenerator\EnumParser.cs" />
<Compile Include="LookupGenerator\EnumToLookup.cs" />
Expand Down
48 changes: 48 additions & 0 deletions EfEnumToLookup/LookupGenerator/ContextExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
namespace EfEnumToLookup.LookupGenerator
{
using System.Data.Entity;
using System.Data.Entity.Core.Metadata.Edm;
using System.Data.Entity.Core.Objects;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Text.RegularExpressions;

public static class ContextExtensions
{
public static string GetTableName<T>(this DbContext context) where T : class
{
var objectContext = ((IObjectContextAdapter)context).ObjectContext;

return objectContext.GetTableName<T>();
}

public static string GetTableName<T>(this ObjectContext context) where T : class
{
string sql = context.CreateObjectSet<T>().ToTraceString();
Regex regex = new Regex("FROM (?<table>.*) AS");
Match match = regex.Match(sql);

string table = match.Groups["table"].Value;
return table;
}

public static string GetDefaultSchema(this DbContext context)
{
////var table = (((IObjectContextAdapter)context).ObjectContext).MetadataWorkspace.GetItems(DataSpace.SSpace).FirstOrDefault();

var table = (((IObjectContextAdapter)context).ObjectContext).MetadataWorkspace.GetItemCollection(DataSpace.SSpace)
.GetItems<EntityContainer>()
.Single()
.BaseEntitySets
.OfType<EntitySet>()
.SingleOrDefault(s => !s.MetadataProperties.Contains("Type") || s.MetadataProperties["Type"].ToString() == "Tables");

if(table == null)
{
return "dbo";
}

return table.MetadataProperties["Schema"].Value.ToString();
}
}
}
9 changes: 2 additions & 7 deletions EfEnumToLookup/LookupGenerator/EnumParser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,8 @@ public IEnumerable<LookupValue> GetLookupValues(Type lookup)
{
Id = (int)numericValue,
Name = EnumName(value),
});
Description = EnumDescriptionValue(value)
});
}
return values;
}
Expand All @@ -70,12 +71,6 @@ public IEnumerable<LookupValue> GetLookupValues(Type lookup)
/// </summary>
private string EnumName(Enum value)
{
var description = EnumDescriptionValue(value);
if (description != null)
{
return description;
}

var name = value.ToString();

if (SplitWords)
Expand Down
78 changes: 43 additions & 35 deletions EfEnumToLookup/LookupGenerator/EnumToLookup.cs
Original file line number Diff line number Diff line change
@@ -1,37 +1,37 @@
namespace EfEnumToLookup.LookupGenerator
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Data.SqlClient;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;

/// <summary>
/// Makes up for a missing feature in Entity Framework 6.1
/// Creates lookup tables and foreign key constraints based on the enums
/// used in your model.
/// Use the properties exposed to control behaviour.
/// Run <c>Apply</c> from your Seed method in either your database initializer
/// or your EF Migrations.
/// It is safe to run repeatedly, and will ensure enum values are kept in line
/// with your current code.
/// Source code: https://github.com/timabell/ef-enum-to-lookup
/// License: MIT
/// </summary>
public class EnumToLookup : IEnumToLookup
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Core.Metadata.Edm;
using System.Data.Entity.Infrastructure;
using System.Data.SqlClient;
using System.Linq;
using System.Reflection;
using System.Text;

/// <summary>
/// Makes up for a missing feature in Entity Framework 6.1
/// Creates lookup tables and foreign key constraints based on the enums
/// used in your model.
/// Use the properties exposed to control behaviour.
/// Run <c>Apply</c> from your Seed method in either your database initializer
/// or your EF Migrations.
/// It is safe to run repeatedly, and will ensure enum values are kept in line
/// with your current code.
/// Source code: https://github.com/timabell/ef-enum-to-lookup
/// License: MIT
/// </summary>
public class EnumToLookup : IEnumToLookup
{
private readonly EnumParser _enumParser;

public EnumToLookup()
{
// set default behaviour, can be overridden by setting properties on object before calling Apply()
NameFieldLength = 255;
TableNamePrefix = "Enum_";
DescriptionFieldLength = 255;
TableNamePrefix = "Enum_";
_enumParser = new EnumParser { SplitWords = true };
}

Expand All @@ -51,12 +51,18 @@ public bool SplitWords
/// </summary>
public int NameFieldLength { get; set; }

/// <summary>
/// Prefix to add to all the generated tables to separate help group them together
/// and make them stand out as different from other tables.
/// Defaults to "Enum_" set to null or "" to not have any prefix.
/// <summary>
/// The size of the Description field that will be added to the generated lookup tables.
/// Adjust to suit your data if required, defaults to 255.
/// </summary>
public string TableNamePrefix { get; set; }
public int DescriptionFieldLength { get; set; }

/// <summary>
/// Prefix to add to all the generated tables to separate help group them together
/// and make them stand out as different from other tables.
/// Defaults to "Enum_" set to null or "" to not have any prefix.
/// </summary>
public string TableNamePrefix { get; set; }

/// <summary>
/// Suffix to add to all the generated tables to separate help group them together
Expand Down Expand Up @@ -110,7 +116,8 @@ private IDbHandler GetDbHandler()
IDbHandler dbHandler = new SqlServerHandler
{
NameFieldLength = NameFieldLength,
TableNamePrefix = TableNamePrefix,
DescriptionFieldLength = DescriptionFieldLength,
TableNamePrefix = TableNamePrefix,
TableNameSuffix = TableNameSuffix,
};
return dbHandler;
Expand All @@ -136,16 +143,17 @@ from enm in enums
NumericType = enm.GetEnumUnderlyingType(),
Values = _enumParser.GetLookupValues(enm),
}).ToList();

var model = new LookupDbModel
{
Lookups = lookups,
References = enumReferences,
};
Schema = context.GetDefaultSchema()
};
return model;
}

private static int ExecuteSqlCommand(DbContext context, string sql, IEnumerable<SqlParameter> parameters = null)
private static int ExecuteSqlCommand(DbContext context, string sql, IEnumerable<SqlParameter> parameters = null)
{
if (parameters == null)
{
Expand Down
14 changes: 10 additions & 4 deletions EfEnumToLookup/LookupGenerator/IDbHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,17 @@ internal interface IDbHandler
/// </summary>
int NameFieldLength { get; set; }

/// <summary>
/// Prefix to add to all the generated tables to separate help group them together
/// and make them stand out as different from other tables.
/// <summary>
/// The size of the Description field that will be added to the generated lookup tables.
/// Adjust to suit your data if required.
/// </summary>
string TableNamePrefix { get; set; }
int DescriptionFieldLength { get; set; }

/// <summary>
/// Prefix to add to all the generated tables to separate help group them together
/// and make them stand out as different from other tables.
/// </summary>
string TableNamePrefix { get; set; }

/// <summary>
/// Suffix to add to all the generated tables to separate help group them together
Expand Down
1 change: 1 addition & 0 deletions EfEnumToLookup/LookupGenerator/LookupDbModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ namespace EfEnumToLookup.LookupGenerator
/// </summary>
internal class LookupDbModel
{
public string Schema { get; set; }
public IList<LookupData> Lookups { get; set; }
public IList<EnumReference> References { get; set; }
}
Expand Down
3 changes: 2 additions & 1 deletion EfEnumToLookup/LookupGenerator/LookupValue.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,6 @@ internal class LookupValue
{
public int Id { get; set; }
public string Name { get; set; }
}
public string Description { get; set; }
}
}
62 changes: 34 additions & 28 deletions EfEnumToLookup/LookupGenerator/SqlServerHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,18 @@ class SqlServerHandler : IDbHandler
/// </summary>
public int NameFieldLength { get; set; }

/// <summary>
/// Prefix to add to all the generated tables to separate help group them together
/// and make them stand out as different from other tables.
/// Defaults to "Enum_" set to null or "" to not have any prefix.
/// <summary>
/// The size of the Description field that will be added to the generated lookup tables.
/// Adjust to suit your data if required, defaults to 255.
/// </summary>
public string TableNamePrefix { get; set; }
public int DescriptionFieldLength { get; set; }

/// <summary>
/// Prefix to add to all the generated tables to separate help group them together
/// and make them stand out as different from other tables.
/// Defaults to "Enum_" set to null or "" to not have any prefix.
/// </summary>
public string TableNamePrefix { get; set; }

/// <summary>
/// Suffix to add to all the generated tables to separate help group them together
Expand All @@ -45,86 +51,86 @@ private string BuildSql(LookupDbModel model)
sql.AppendLine("set nocount on;");
sql.AppendLine("set xact_abort on; -- rollback on error");
sql.AppendLine("begin tran;");
sql.AppendLine(CreateTables(model.Lookups));
sql.AppendLine(PopulateLookups(model.Lookups));
sql.AppendLine(AddForeignKeys(model.References));
sql.AppendLine(CreateTables(model.Lookups, model.Schema));
sql.AppendLine(PopulateLookups(model.Lookups, model.Schema));
sql.AppendLine(AddForeignKeys(model.References, model.Schema));
sql.AppendLine("commit;");
return sql.ToString();
}

private string CreateTables(IEnumerable<LookupData> enums)
private string CreateTables(IEnumerable<LookupData> enums, string schema)
{
var sql = new StringBuilder();

foreach (var lookup in enums)
{
{
sql.AppendFormat(
@"IF OBJECT_ID('{0}', 'U') IS NULL
@"IF OBJECT_ID('{0}', 'U') IS NULL
begin
CREATE TABLE [{0}] (Id {2} CONSTRAINT PK_{0} PRIMARY KEY, Name nvarchar({1}));
exec sys.sp_addextendedproperty @name=N'MS_Description', @level0type=N'SCHEMA', @level0name=N'dbo', @level1type=N'TABLE',
CREATE TABLE [{4}].[{0}] (Id {2} CONSTRAINT PK_{0} PRIMARY KEY, Name nvarchar({1}), Description nvarchar({3}));
exec sys.sp_addextendedproperty @name=N'MS_Description', @level0type=N'SCHEMA', @level0name=N'{4}', @level1type=N'TABLE',
@level1name=N'{0}', @value=N'Automatically generated. Contents will be overwritten on app startup. Table & contents generated by https://github.com/timabell/ef-enum-to-lookup';
end
",
TableName(lookup.Name), NameFieldLength, NumericSqlType(lookup.NumericType));
TableName(lookup.Name), NameFieldLength, NumericSqlType(lookup.NumericType), DescriptionFieldLength, schema);
}
return sql.ToString();
}

private string AddForeignKeys(IEnumerable<EnumReference> refs)
private string AddForeignKeys(IEnumerable<EnumReference> refs, string schema)
{
var sql = new StringBuilder();
foreach (var enumReference in refs)
{
var fkName = string.Format("FK_{0}_{1}", enumReference.ReferencingTable, enumReference.ReferencingField);

sql.AppendFormat(
" IF OBJECT_ID('{0}', 'F') IS NULL ALTER TABLE [{1}] ADD CONSTRAINT {0} FOREIGN KEY ([{2}]) REFERENCES [{3}] (Id);\r\n",
fkName, enumReference.ReferencingTable, enumReference.ReferencingField, TableName(enumReference.EnumType.Name)
);
" IF OBJECT_ID('{0}', 'F') IS NULL ALTER TABLE [{4}].[{1}] ADD CONSTRAINT {0} FOREIGN KEY ([{2}]) REFERENCES [{4}].[{3}] (Id);\r\n",
fkName, enumReference.ReferencingTable, enumReference.ReferencingField, TableName(enumReference.EnumType.Name), schema);
}
return sql.ToString();
}

private string PopulateLookups(IEnumerable<LookupData> lookupData)
private string PopulateLookups(IEnumerable<LookupData> lookupData, string schema)
{
var sql = new StringBuilder();
sql.AppendLine(string.Format("CREATE TABLE #lookups (Id int, Name nvarchar({0}) COLLATE database_default);", NameFieldLength));
sql.AppendLine(string.Format("CREATE TABLE #lookups (Id int, Name nvarchar({0}), Description nvarchar({1}) COLLATE database_default);", NameFieldLength, DescriptionFieldLength));
foreach (var lookup in lookupData)
{
sql.AppendLine(PopulateLookup(lookup));
sql.AppendLine(PopulateLookup(lookup, schema));
}
sql.AppendLine("DROP TABLE #lookups;");
return sql.ToString();
}

private string PopulateLookup(LookupData lookup)
private string PopulateLookup(LookupData lookup, string schema)
{
var sql = new StringBuilder();
foreach (var value in lookup.Values)
{
sql.AppendFormat("INSERT INTO #lookups (Id, Name) VALUES ({0}, N'{1}');\r\n", value.Id, SanitizeSqlString(value.Name));
sql.AppendFormat("INSERT INTO #lookups (Id, Name, Description) VALUES ({0}, N'{1}', N'{2}');\r\n", value.Id, SanitizeSqlString(value.Name), SanitizeSqlString(value.Description));
}

sql.AppendLine(string.Format(@"
MERGE INTO [{0}] dst
MERGE INTO [{1}].[{0}] dst
USING #lookups src ON src.Id = dst.Id
WHEN MATCHED AND src.Name <> dst.Name THEN
UPDATE SET Name = src.Name
WHEN NOT MATCHED THEN
INSERT (Id, Name)
VALUES (src.Id, src.Name)
INSERT (Id, Name, Description)
Copy link
Owner

Choose a reason for hiding this comment

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

this won't pick up changes in description due to the "when matched" clause above

Copy link
Author

Choose a reason for hiding this comment

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

My bad. The "when matched" needs to be updated to catch description changes.

Copy link
Owner

Choose a reason for hiding this comment

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

this indicates we could do with extending the test suite to cover add/remove/updating the lookup rows in the db as the model is changed.

plan: run apply, directly manipulate the db to add/edit/remove, assert changed (just to avoid false positive if this step silently failed), run apply again, assert that table was returned to original state

VALUES (src.Id, src.Name, src.Description)
WHEN NOT MATCHED BY SOURCE THEN
DELETE
;"
, TableName(lookup.Name)));
, TableName(lookup.Name), schema));

sql.AppendLine("TRUNCATE TABLE #lookups;");
return sql.ToString();
}

private static string SanitizeSqlString(string value)
{
return value.Replace("'", "''");
return value == null ? null : value.Replace("'", "''");
}

private string TableName(string enumName)
Expand Down
2 changes: 1 addition & 1 deletion EfEnumToLookup/Properties/AssemblyInfo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,6 @@
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.8.0.0")]
[assembly: AssemblyFileVersion("2.0.0.0")]

[assembly:InternalsVisibleTo("EfEnumToLookupTests,PublicKey=002400000480000094000000060200000024000052534131000400000100010099a4b9a877a10f75bc4c1a9bf08ee9e21a2df3b9746f2535505b77b3f82971aa8a07caa6cd60b9df6e4b2982ebdb78da960ec1e7688a3b56b6da65e05783ee51f345b1cf0e5a38a02f3cc7c1763d7e469edafc59ef8c21b1a9bcca8548973429577362d992e4a6ed001cb28dc54ecc7ef298e94676bd918fd9e9b521e0cb7ae5")]
2 changes: 1 addition & 1 deletion EfEnumToLookupTests/App.config
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="v11.0" />
<parameter value="ProjectsV12" />
</parameters>
</defaultConnectionFactory>
<providers>
Expand Down
Loading