public void Fragment_MethodCallCodeFragment_works_when_chaining() { var method = new MethodCallCodeFragment(_testFuncMethodInfo) .Chain(_testFuncMethodInfo); var result = new CSharpHelper(TypeMappingSource).Fragment(method); Assert.Equal($".TestFunc(){EOL}.TestFunc()", result); }
public void Declare2(string expected, Type type) { var csharp = new CSharpHelper(); using (csharp.BeginNamespaceDeclaration("Fsi.TextTemplating")) { Assert.Equal(expected, csharp.NameOf(type)); } }
protected void TypeOfNameOf(string expected, Type type) { var csharp = new CSharpHelper(); csharp.Import("System"); csharp.Import("System.Threading"); Assert.Equal(expected, csharp.TypeOfNameOf(type)); Assert.Equal(expected, csharp.TypeOfNameOf(type)); }
public void Snapshots_compile() { var codeHelper = new CSharpHelper(); var generator = new CSharpMigrationGenerator( codeHelper, new CSharpMigrationOperationGenerator(codeHelper), new CSharpModelGenerator(codeHelper)); var modelSnapshotCode = generator.GenerateSnapshot("MyNamespace", typeof(MyContext), "MySnapshot", new Model()); Assert.Equal(@"using System; using Microsoft.Data.Entity; using Microsoft.Data.Entity.Metadata; using Microsoft.Data.Entity.Relational.Migrations.Infrastructure; using Microsoft.Data.Entity.Commands.Migrations; namespace MyNamespace { [ContextType(typeof(CodeCompilationTest.MyContext))] partial class MySnapshot : ModelSnapshot { public override void BuildModel(ModelBuilder builder) { } } } ", modelSnapshotCode); var build = new BuildSource { References = { BuildReference.ByName(typeof(CodeCompilationTest).Assembly.GetName().Name), BuildReference.ByName("System.Runtime, Version=4.0.10.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"), BuildReference.ByName("EntityFramework.Core"), BuildReference.ByName("EntityFramework.Relational") }, Sources = { modelSnapshotCode } }; var assembly = build.BuildInMemory(); var snapshotType = assembly.GetType("MyNamespace.MySnapshot", throwOnError: true); var contextTypeAttribute = snapshotType.GetCustomAttribute <ContextTypeAttribute>(); Assert.NotNull(contextTypeAttribute); Assert.Equal(typeof(MyContext), contextTypeAttribute.ContextType); var snapshot = (ModelSnapshot)Activator.CreateInstance(snapshotType); var conventions = new ConventionSet(); var modelBuilder = new ModelBuilder(conventions); snapshot.BuildModel(modelBuilder); Assert.Empty(modelBuilder.Model.EntityTypes); }
/// <summary> /// Generate OnConfiguring method. /// </summary> /// <param name="connectionString">Database connection string.</param> /// <param name="suppressConnectionStringWarning">Suppress connection string warning.</param> protected override void GenerateOnConfiguring(string connectionString, bool suppressConnectionStringWarning) { Check.NotNull(connectionString, nameof(connectionString)); var sb = new IndentedStringBuilder(); using (sb.Indent()) using (sb.Indent()) { sb.AppendLine("protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)"); sb.AppendLine("{"); using (sb.Indent()) { sb.AppendLine("if (!optionsBuilder.IsConfigured)"); sb.AppendLine("{"); using (sb.Indent()) { if (!suppressConnectionStringWarning) { sb.DecrementIndent() .DecrementIndent() .DecrementIndent() .DecrementIndent() .AppendLine("#warning " + DesignStrings.SensitiveInformationWarning) .IncrementIndent() .IncrementIndent() .IncrementIndent() .IncrementIndent(); } sb.Append("optionsBuilder"); var useProviderCall = ProviderConfigurationCodeGenerator.GenerateUseProvider( connectionString, ProviderConfigurationCodeGenerator.GenerateProviderOptions()); var contextOptions = ProviderConfigurationCodeGenerator.GenerateContextOptions(); if (contextOptions != null) { useProviderCall = useProviderCall.Chain(contextOptions); } sb.Append(CSharpHelper.Fragment(useProviderCall)) .AppendLine(";"); } sb.AppendLine("}"); } sb.AppendLine("}"); } var onConfiguring = sb.ToString(); TemplateData.Add("on-configuring", onConfiguring); }
/// <summary> /// Generate OnConfiguring method. /// </summary> /// <param name="connectionString">Database connection string.</param> /// <param name="suppressConnectionStringWarning">Suppress connection string warning.</param> protected virtual void GenerateOnConfiguring( string connectionString, bool suppressConnectionStringWarning) { if (connectionString == null) { throw new ArgumentNullException(nameof(connectionString)); } var sb = new IndentedStringBuilder(); using (sb.Indent()) { sb.IncrementIndent(); sb.AppendLine("protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)"); sb.AppendLine("{"); using (sb.Indent()) { sb.AppendLine("if (!optionsBuilder.IsConfigured)"); sb.AppendLine("{"); using (sb.Indent()) { if (!suppressConnectionStringWarning) { sb.DecrementIndent() .DecrementIndent() .DecrementIndent() .DecrementIndent() .AppendLine("#warning " + DesignStrings.SensitiveInformationWarning) .IncrementIndent() .IncrementIndent() .IncrementIndent() .IncrementIndent(); } sb.Append("optionsBuilder") .Append( ProviderConfigurationCodeGenerator != null ? CSharpHelper.Fragment( ProviderConfigurationCodeGenerator.GenerateUseProvider(connectionString, null)) #pragma warning disable CS0618 // Type or member is obsolete : LegacyProviderCodeGenerator.GenerateUseProvider(connectionString, Language)) #pragma warning restore CS0618 // Type or member is obsolete .AppendLine(";"); } sb.AppendLine("}"); } sb.AppendLine("}"); var onConfiguring = sb.ToString(); TemplateData.Add("on-configuring", onConfiguring); } }
private void GenerateIndex(IIndex index, IndentedStringBuilder sb) { var lines = new List <string> { $".{nameof(EntityTypeBuilder.HasIndex)}(e => {GenerateLambdaToKey(index.Properties, "e")})" }; var annotations = index.GetAnnotations().ToList(); if (!string.IsNullOrEmpty((string)index[RelationalAnnotationNames.Name])) { lines.Add( $".{nameof(RelationalIndexBuilderExtensions.HasName)}" + $"({CSharpHelper.Literal(index.Relational().Name)})"); RemoveAnnotation(ref annotations, RelationalAnnotationNames.Name); } if (index.IsUnique) { lines.Add($".{nameof(IndexBuilder.IsUnique)}()"); } if (index.Relational().Filter != null) { lines.Add( $".{nameof(RelationalIndexBuilderExtensions.HasFilter)}" + $"({CSharpHelper.Literal(index.Relational().Filter)})"); RemoveAnnotation(ref annotations, RelationalAnnotationNames.Filter); } var annotationsToRemove = new List <IAnnotation>(); foreach (var annotation in annotations) { if (CodeGenerator.IsHandledByConvention(index, annotation)) { annotationsToRemove.Add(annotation); } else { #pragma warning disable CS0618 // Type or member is obsolete var line = CodeGenerator.GenerateFluentApi(index, annotation, Language); #pragma warning restore CS0618 // Type or member is obsolete if (line != null) { lines.Add(line); annotationsToRemove.Add(annotation); } } } lines.AddRange(GenerateAnnotations(annotations.Except(annotationsToRemove))); AppendMultiLineFluentApi(index.DeclaringEntityType, lines, sb); }
public void Snapshots_compile() { var codeHelper = new CSharpHelper(); var generator = new CSharpMigrationsGenerator( codeHelper, new CSharpMigrationOperationGenerator(codeHelper), new CSharpSnapshotGenerator(codeHelper)); var model = new Model { ["Some:EnumValue"] = RegexOptions.Multiline }; var entityType = model.AddEntityType("Cheese"); entityType.AddProperty("Pickle", typeof(StringBuilder)); var modelSnapshotCode = generator.GenerateSnapshot( "MyNamespace", typeof(MyContext), "MySnapshot", model); Assert.Equal(@"// <auto-generated /> using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Design.Tests.Migrations.Design; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; using System; using System.Text; using System.Text.RegularExpressions; namespace MyNamespace { [DbContext(typeof(CSharpMigrationsGeneratorTest.MyContext))] partial class MySnapshot : ModelSnapshot { protected override void BuildModel(ModelBuilder modelBuilder) { modelBuilder .HasAnnotation(""Some:EnumValue"", RegexOptions.Multiline); modelBuilder.Entity(""Cheese"", b => { b.Property<StringBuilder>(""Pickle""); b.ToTable(""Cheese""); }); } } } ", modelSnapshotCode); var snapshot = CompileModelSnapshot(modelSnapshotCode, "MyNamespace.MySnapshot"); Assert.Equal(1, snapshot.Model.GetEntityTypes().Count()); }
public void Fragment_MethodCallCodeFragment_works_when_nested_closure() { var method = new MethodCallCodeFragment( _testFuncMethodInfo, new NestedClosureCodeFragment("x", new MethodCallCodeFragment(_testFuncMethodInfo))); var result = new CSharpHelper(TypeMappingSource).Fragment(method); Assert.Equal(".TestFunc(x => x.TestFunc())", result); }
public void Fragment_MethodCallCodeFragment_works_when_chaining_on_chain() { var method = new MethodCallCodeFragment(_testFuncMethodInfo, "One") .Chain(new MethodCallCodeFragment(_testFuncMethodInfo, "Two")) .Chain(_testFuncMethodInfo, "Three"); var result = new CSharpHelper(TypeMappingSource).Fragment(method); Assert.Equal(@$ ".TestFunc(" "One" "){EOL}.TestFunc(" "Two" "){EOL}.TestFunc(" "Three" ")", result); }
public void NamespaceDisposeTwice() { var csharp = new CSharpHelper(); using (var ns = csharp.BeginNamespaceDeclaration("Fsi")) { ns.Dispose(); } Assert.Equal("int", csharp.NameOf(typeof(int))); }
private static List <TreeItem <MemberInfo> > Collect(string code) { var assemblyName = Guid.NewGuid().ToString(); var syntaxTree = CSharpCompiler.ParseText(code); var(_, assembly) = CSharpCompiler.Compile(assemblyName, syntaxTree); var syntaxItems = CSharpHelper.CollectSyntax(syntaxTree.GetRoot()); return(CSharpHelper.CollectMembers(assembly, syntaxItems)); }
public void TypeOfNameArgNull() { var csharp = new CSharpHelper(); Assert.Throws <ArgumentNullException>("type", () => { csharp.AppendTypeOfNameTo(default(Type), new StringBuilder()); }); Assert.Throws <ArgumentNullException>("typeName", () => { csharp.AppendTypeOfNameTo(typeof(int), default(StringBuilder)); }); Assert.Throws <ArgumentNullException>("type", () => { csharp.TypeOfNameOf(default(Type)); }); }
private void GenerateIndex(IIndex index, IndentedStringBuilder sb) { var lines = new List <string> { $".{nameof(EntityTypeBuilder.HasIndex)}(e => {GenerateLambdaToKey(index.Properties, "e")})" }; var annotations = index.GetAnnotations().ToList(); if (!string.IsNullOrEmpty((string)index[RelationalAnnotationNames.Name])) { lines.Add( $".{nameof(RelationalIndexBuilderExtensions.HasName)}" + $"({CSharpHelper.Literal(index.GetName())})"); RemoveAnnotation(ref annotations, RelationalAnnotationNames.Name); } if (index.IsUnique) { lines.Add($".{nameof(IndexBuilder.IsUnique)}()"); } if (index.GetFilter() != null) { lines.Add( $".{nameof(RelationalIndexBuilderExtensions.HasFilter)}" + $"({CSharpHelper.Literal(index.GetFilter())})"); RemoveAnnotation(ref annotations, RelationalAnnotationNames.Filter); } var annotationsToRemove = new List <IAnnotation>(); foreach (var annotation in annotations) { if (annotation.Value == null || AnnotationCodeGenerator.IsHandledByConvention(index, annotation)) { annotationsToRemove.Add(annotation); } else { var methodCall = AnnotationCodeGenerator.GenerateFluentApi(index, annotation); if (methodCall != null) { lines.Add(CSharpHelper.Fragment(methodCall)); annotationsToRemove.Add(annotation); } } } lines.AddRange(GenerateAnnotations(annotations.Except(annotationsToRemove))); AppendMultiLineFluentApi(index.DeclaringEntityType, lines, sb); }
public void DecimalArgumentError(short value, int groupSize, int minDigits, string paramName, string message) { var ex = Assert.Throws <ArgumentException>(paramName, () => { var csharp = new CSharpHelper(); csharp.Decimal(value, groupSize, minDigits); }); Assert.Equal(message + $"\r\nParameter name: {paramName}", ex.Message); }
public void GenericParameterTypeName() { var parameters = typeof(Func <, , , ,>).GetTypeInfo().GenericTypeParameters; var csharp = new CSharpHelper(); Assert.Equal("T1", csharp.AliasNameOf(parameters[0])); Assert.Equal("T2", csharp.CRefNameOf(parameters[1])); Assert.Equal("T3", csharp.FullNameOf(parameters[2])); Assert.Equal("T4", csharp.NameOf(parameters[3])); Assert.Equal(string.Empty, csharp.TypeOfNameOf(parameters[4])); }
public void Literal_works_when_MultidimensionalArray() { var value = new object[, ] { { 'A', 1 }, { 'B', 2 } }; var result = new CSharpHelper(TypeMappingSource).Literal(value); Assert.Equal( "new object[,]" + EOL + "{" + EOL + " { 'A', 1 }," + EOL + " { 'B', 2 }" + EOL + "}", result); }
/// <summary> /// 新增一筆資料並更新 Identity /// </summary> public virtual bool Insert(T model, IEnumerable <string> columns) { var cmd = SqlCommandHelper.GenerateInsert(model, columns); object identity = SqlHelper.ExecuteScalar(cmd); if (identity != null && identity != DBNull.Value) { var prop = CSharpHelper.GetIdentityProperty <T>(); prop.SetValue(model, identity); } return(true); }
public void GenerateForInterface(CSharpWriter stream, Nodes.UmlAttributeNode attributeNode) { stream.WriteSummary(attributeNode.Documentation); if (attributeNode.IsReadOnly) { stream.WriteCodeLine($"{CSharpHelper.ResolveType(attributeNode)} {attributeNode.Name} {{ get; }}"); } else { stream.WriteCodeLine($"{CSharpHelper.ResolveType(attributeNode)} {attributeNode.Name} {{ get; set; }}"); } }
protected virtual void Test_GenerateCodeLiteral_helper( RelationalTypeMapping typeMapping, object value, string expectedCode) { var typeMappingSource = new SqlServerTypeMappingSource( TestServiceFactory.Instance.Create <TypeMappingSourceDependencies>(), TestServiceFactory.Instance.Create <RelationalTypeMappingSourceDependencies>()); var csharpHelper = new CSharpHelper(typeMappingSource); Assert.Equal(expectedCode, csharpHelper.UnknownLiteral(value)); }
public CSharpMigrationGenerator( [NotNull] CSharpHelper code, [NotNull] CSharpMigrationOperationGenerator operationGenerator, [NotNull] CSharpModelGenerator modelGenerator) { Check.NotNull(code, nameof(code)); Check.NotNull(operationGenerator, nameof(operationGenerator)); Check.NotNull(modelGenerator, nameof(modelGenerator)); _code = code; _operationGenerator = operationGenerator; _modelGenerator = modelGenerator; }
public void NullableProperties() { // NOTE: // // This test doesn't work due to apparent limitations of // the DataWrapper class an perhaps .NET itself. The problem // is related to assigning a nullable Enum value. This // fails even though I explicitly cast the value to (MyEnum1?). // // I think the problem is related to the JIT compiler doing some // magic here and effectively stripping out the cast and // just passing the non-nullable enum value and then // [DataWrapper] fails when dynamically assigning the value // to the property because the value is no longer a (MyEnum1?). // // I have verified this manually when using the generated // model classes directly. // Verify that we handle nullable property types correctly. var settings = new ModelGeneratorSettings() { SourceNamespace = typeof(Test_UxDataModel).Namespace, UxFramework = UxFrameworks.Xaml }; var generator = new ModelGenerator(settings); var output = generator.Generate(Assembly.GetExecutingAssembly()); Assert.False(output.HasErrors); var assemblyStream = CSharpHelper.Compile(output.SourceCode, "test-assembly", references => ModelGenTestHelper.ReferenceHandler(references)); using (var context = new AssemblyContext("Neon.ModelGen.Output", assemblyStream)) { var data = context.CreateDataWrapper <NullableProperties>(); Assert.Equal("{\"Bool\":null,\"Int\":null,\"Enum\":null}", data.ToString()); data = context.CreateDataWrapperFrom <NullableProperties>(data.ToString()); Assert.Equal("{\"Bool\":null,\"Int\":null,\"Enum\":null}", data.ToString()); data["Bool"] = true; data["Int"] = 100; data["Enum"] = (MyEnum1?)MyEnum1.Two; // This throws an exception var s = data.ToString(); Assert.Equal("", data.ToString()); } }
protected void AppendTypeOfNameTo(string expected, Type type) { var csharp = new CSharpHelper(); csharp.Import("System"); csharp.Import("System.Threading"); var typeName = new StringBuilder(type.Name.Length); csharp.AppendTypeOfNameTo(type, typeName); Assert.Equal(expected, typeName.ToString()); typeName.Clear(); csharp.AppendTypeOfNameTo(type, typeName); Assert.Equal(expected, typeName.ToString()); }
internal void GenerateForClass(CSharpWriter stream, UmlAttributeNode attributeNode) { stream.WriteSummary(attributeNode.Documentation); var visibility = CSharpHelper.ConvertVisibility(attributeNode.Visibility, true, true); var attrType = CSharpHelper.ResolveType(attributeNode); if (attributeNode.IsReadOnly) { stream.WriteCodeLine($"{visibility} {attrType} {attributeNode.Name} {{ get; private set; }}"); } else { stream.WriteCodeLine($"{visibility} {attrType} {attributeNode.Name} {{ get; set; }}"); } }
internal void GenerateForClass(CSharpWriter stream, UmlAssociationEndNode associationEndNode) { stream.WriteSummary(associationEndNode.Documentation); var visibility = CSharpHelper.ConvertVisibility(associationEndNode.Visibility, true, true); var opositeType = CSharpHelper.ResolveType(associationEndNode.OpositeEnd); if (associationEndNode.IsReadOnly) { stream.WriteCodeLine($"{visibility} IEnumerable<{opositeType}> {associationEndNode.Name} {{ get; private set; }}"); } else { stream.WriteCodeLine($"{visibility} IEnumerable<{opositeType}> {associationEndNode.Name} {{ get; set; }}"); } }
protected override void GenerateProperties(IEntityType entityType) { var properties = new List <Dictionary <string, object> >(); #pragma warning disable EF1001 // Internal EF Core API usage. foreach (var property in entityType.GetProperties().OrderBy(p => p.GetColumnOrdinal())) #pragma warning restore EF1001 // Internal EF Core API usage. { PropertyAnnotationsData = new List <Dictionary <string, object> >(); if (UseDataAnnotations) { GeneratePropertyDataAnnotations(property); } var propertyType = CSharpHelper.Reference(property.ClrType); if (_options?.Value?.EnableNullableReferenceTypes == true && property.IsNullable && !propertyType.EndsWith("?")) { propertyType += "?"; } properties.Add(new Dictionary <string, object> { { "property-type", propertyType }, { "property-name", property.Name }, { "property-annotations", PropertyAnnotationsData }, { "property-comment", property.GetComment() }, { "property-isnullable", property.IsNullable }, { "nullable-reference-types", _options?.Value?.EnableNullableReferenceTypes == true }, // Add new item to template data { "property-isprimarykey", property.IsPrimaryKey() } }); } var transformedProperties = EntityTypeTransformationService.TransformProperties(properties); // Add to transformed properties for (int i = 0; i < transformedProperties.Count; i++) { transformedProperties[i].Add("property-isprimarykey", properties[i]["property-isprimarykey"]); } TemplateData.Add("properties", transformedProperties); }
private string GetOnConfiguring(string connectionString, bool suppressConnectionStringWarning) { var sb = new IndentedStringBuilder(); using (sb.Indent()) using (sb.Indent()) { sb.AppendLine("protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)"); sb.AppendLine("{"); using (sb.Indent()) { sb.AppendLine("if (!optionsBuilder.IsConfigured)"); sb.AppendLine("{"); using (sb.Indent()) { if (!suppressConnectionStringWarning) { sb.DecrementIndent() .DecrementIndent() .DecrementIndent() .DecrementIndent() .AppendLine("#warning " + DesignStrings.SensitiveInformationWarning) .IncrementIndent() .IncrementIndent() .IncrementIndent() .IncrementIndent(); } sb.Append("optionsBuilder"); var useProviderCall = ProviderConfigurationCodeGenerator.GenerateUseProvider(connectionString); sb.Append(CSharpHelper.Fragment(useProviderCall)) .AppendLine(";"); } sb.AppendLine("}"); } sb.AppendLine("}"); } return(sb.ToString()); }
private void GenerateTableName(IEntityType entityType, IndentedStringBuilder sb) { var tableName = entityType.GetTableName(); var schema = entityType.GetSchema(); var defaultSchema = entityType.Model.GetDefaultSchema(); var explicitSchema = schema != null && schema != defaultSchema; var explicitTable = explicitSchema || tableName != null && tableName != entityType.GetDbSetName(); if (explicitTable) { var parameterString = CSharpHelper.Literal(tableName); if (explicitSchema) { parameterString += ", " + CSharpHelper.Literal(schema); } var lines = new List <string> { $".{nameof(RelationalEntityTypeBuilderExtensions.ToTable)}({parameterString})" }; AppendMultiLineFluentApi(entityType, lines, sb); } var viewName = entityType.GetViewName(); var viewSchema = entityType.GetViewSchema(); var explicitViewSchema = viewSchema != null && viewSchema != defaultSchema; var explicitViewTable = explicitViewSchema || viewName != null; if (explicitViewTable) { var parameterString = CSharpHelper.Literal(viewName); if (explicitViewSchema) { parameterString += ", " + CSharpHelper.Literal(viewSchema); } var lines = new List <string> { $".{nameof(RelationalEntityTypeBuilderExtensions.ToView)}({parameterString})" }; AppendMultiLineFluentApi(entityType, lines, sb); } }
public void HexaDecimalError(short value, int groupSize, int minDigits, Type exceptionType, string paramName, string message) { Assert.Throws(exceptionType, () => { try { var csharp = new CSharpHelper(); csharp.HexaDecimal(value, groupSize, minDigits); } catch (ArgumentException ex) { Assert.Equal(paramName, ex.ParamName); Assert.Equal(message + $"\r\nParameter name: {paramName}", ex.Message); throw; } }); }
private static List <Disassembler> GetFileDisassemblers(DisassembleFileOptions options, MessageWriter writer) { var begin = DateTime.Now; // Parsing writer.Write("; Parsing from file ... "); var syntaxTree = CSharpCompiler.ParseFrom(options.FilePath); var parsed = DateTime.Now; writer.WriteLine($"done. ({Diff(begin, parsed)})"); // Compiling writer.Write("; Compiling ... "); var compilationOptions = new CompilationOptions { SaveAssembly = options.SaveAssembly, DisableOptimization = options.DisableOptimization }; var assemblyName = Path.GetFileNameWithoutExtension(options.FilePath); var(_, assembly) = CSharpCompiler.Compile(assemblyName, syntaxTree, compilationOptions); var compiled = DateTime.Now; writer.WriteLine($"done. ({Diff(parsed, compiled)})"); // Analyzing writer.Write("; Analyzing ... "); var syntaxItems = CSharpHelper.CollectSyntax(syntaxTree.GetRoot()); var memberItems = CSharpHelper.CollectMembers(assembly, syntaxItems); var disassemblers = memberItems.Select(Disassembler.Create).ToList(); var analyzed = DateTime.Now; writer.WriteLine($"done. ({Diff(compiled, analyzed)})"); writer.WriteLine(""); return(disassemblers); }
public void Snapshot_with_default_values_are_round_tripped() { var codeHelper = new CSharpHelper(); var generator = new CSharpMigrationsGenerator( codeHelper, new CSharpMigrationOperationGenerator(codeHelper), new CSharpSnapshotGenerator(codeHelper)); var modelBuilder = new ModelBuilder(new CoreConventionSetBuilder().CreateConventionSet()); modelBuilder.Entity<EntityWithEveryPrimitive>(eb => { eb.Property(e => e.Boolean).HasDefaultValue(false); eb.Property(e => e.Byte).HasDefaultValue((byte)0); eb.Property(e => e.ByteArray).HasDefaultValue(new byte[] { 0 }); eb.Property(e => e.Char).HasDefaultValue('0'); eb.Property(e => e.DateTime).HasDefaultValue(new DateTime(1980, 1, 1)); eb.Property(e => e.DateTimeOffset).HasDefaultValue(new DateTimeOffset(1980, 1, 1, 0, 0, 0, new TimeSpan(0, 0, 0))); eb.Property(e => e.Decimal).HasDefaultValue(0m); eb.Property(e => e.Double).HasDefaultValue(0.0); eb.Property(e => e.Enum).HasDefaultValue(Enum1.Default); eb.Property(e => e.Guid).HasDefaultValue(new Guid()); eb.Property(e => e.Int16).HasDefaultValue((short)0); eb.Property(e => e.Int32).HasDefaultValue(0); eb.Property(e => e.Int64).HasDefaultValue(0L); eb.Property(e => e.Single).HasDefaultValue((float)0.0); eb.Property(e => e.SByte).HasDefaultValue((sbyte)0); eb.Property(e => e.String).HasDefaultValue("'\"'"); eb.Property(e => e.TimeSpan).HasDefaultValue(new TimeSpan(0, 0, 0)); eb.Property(e => e.UInt16).HasDefaultValue((ushort)0); eb.Property(e => e.UInt32).HasDefaultValue(0U); eb.Property(e => e.UInt64).HasDefaultValue(0UL); eb.Property(e => e.NullableBoolean).HasDefaultValue(true); eb.Property(e => e.NullableByte).HasDefaultValue(byte.MaxValue); eb.Property(e => e.NullableChar).HasDefaultValue('\''); eb.Property(e => e.NullableDateTime).HasDefaultValue(new DateTime(1900, 12, 31)); eb.Property(e => e.NullableDateTimeOffset).HasDefaultValue(new DateTimeOffset(3000, 1, 1, 0, 0, 0, new TimeSpan(0, 0, 0))); eb.Property(e => e.NullableDecimal).HasDefaultValue(2m * long.MaxValue); eb.Property(e => e.NullableDouble).HasDefaultValue(0.6822871999174); eb.Property(e => e.NullableEnum).HasDefaultValue(Enum1.Default); eb.Property(e => e.NullableGuid).HasDefaultValue(new Guid()); eb.Property(e => e.NullableInt16).HasDefaultValue(short.MinValue); eb.Property(e => e.NullableInt32).HasDefaultValue(int.MinValue); eb.Property(e => e.NullableInt64).HasDefaultValue(long.MinValue); eb.Property(e => e.NullableSingle).HasDefaultValue(0.3333333f); eb.Property(e => e.NullableSByte).HasDefaultValue(sbyte.MinValue); eb.Property(e => e.NullableTimeSpan).HasDefaultValue(new TimeSpan(-1, 0, 0)); eb.Property(e => e.NullableUInt16).HasDefaultValue(ushort.MaxValue); eb.Property(e => e.NullableUInt32).HasDefaultValue(uint.MaxValue); eb.Property(e => e.NullableUInt64).HasDefaultValue(ulong.MaxValue); }); var modelSnapshotCode = generator.GenerateSnapshot( "MyNamespace", typeof(MyContext), "MySnapshot", modelBuilder.Model); var snapshot = CompileModelSnapshot(modelSnapshotCode, "MyNamespace.MySnapshot"); var entityType = snapshot.Model.GetEntityTypes().Single(); Assert.Equal(typeof(EntityWithEveryPrimitive).FullName, entityType.DisplayName()); foreach (var property in modelBuilder.Model.GetEntityTypes().Single().GetProperties()) { var snapshotProperty = entityType.FindProperty(property.Name); Assert.Equal(property.Relational().DefaultValue, snapshotProperty.Relational().DefaultValue); } }
public void Literal_works(object value, string expected) { var literal = new CSharpHelper().UnknownLiteral(value); Assert.Equal(expected, literal); }
public void Literal_works_when_single_StringArray() { var literal = new CSharpHelper().Literal(new[] { "A" }); Assert.Equal("\"A\"", literal); }
public void Literal_works_when_many_StringArray() { var literal = new CSharpHelper().Literal(new[] { "A", "B" }); Assert.Equal("new[] { \"A\", \"B\" }", literal); }
public void Snapshots_compile() { var codeHelper = new CSharpHelper(); var generator = new CSharpMigrationsGenerator( codeHelper, new CSharpMigrationOperationGenerator(codeHelper), new CSharpSnapshotGenerator(codeHelper)); var modelSnapshotCode = generator.GenerateSnapshot( "MyNamespace", typeof(MyContext), "MySnapshot", new Model {["Some:EnumValue"] = RegexOptions.Multiline }); Assert.Equal(@"using System; using Microsoft.Data.Entity; using Microsoft.Data.Entity.Infrastructure; using Microsoft.Data.Entity.Metadata; using Microsoft.Data.Entity.Migrations; using Microsoft.Data.Entity.Commands.Migrations; using System.Text.RegularExpressions; namespace MyNamespace { [DbContext(typeof(CodeCompilationTest.MyContext))] partial class MySnapshot : ModelSnapshot { protected override void BuildModel(ModelBuilder modelBuilder) { modelBuilder .Annotation(""Some:EnumValue"", RegexOptions.Multiline); } } } ", modelSnapshotCode); var build = new BuildSource { References = { BuildReference.ByName(typeof(CodeCompilationTest).GetTypeInfo().Assembly.GetName().Name), #if DNXCORE50 BuildReference.ByName("System.Text.RegularExpressions"), #else BuildReference.ByName("System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"), BuildReference.ByName("System.Runtime, Version=4.0.10.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"), #endif BuildReference.ByName("EntityFramework.Core"), BuildReference.ByName("EntityFramework.Relational") }, Sources = { modelSnapshotCode } }; var assembly = build.BuildInMemory(); var snapshotType = assembly.GetType("MyNamespace.MySnapshot", throwOnError: true, ignoreCase: false); var contextTypeAttribute = snapshotType.GetTypeInfo().GetCustomAttribute<DbContextAttribute>(); Assert.NotNull(contextTypeAttribute); Assert.Equal(typeof(MyContext), contextTypeAttribute.ContextType); var snapshot = (ModelSnapshot)Activator.CreateInstance(snapshotType); Assert.Empty(snapshot.Model.EntityTypes); }
public void Migrations_compile() { var codeHelper = new CSharpHelper(); var generator = new CSharpMigrationsGenerator( codeHelper, new CSharpMigrationOperationGenerator(codeHelper), new CSharpSnapshotGenerator(codeHelper)); var migrationCode = generator.GenerateMigration( "MyNamespace", "MyMigration", new[] { new SqlOperation { Sql = "-- TEST", ["Some:EnumValue"] = RegexOptions.Multiline } }, new MigrationOperation[0]); Assert.Equal( @"using System; using System.Collections.Generic; using Microsoft.Data.Entity.Migrations; using System.Text.RegularExpressions; namespace MyNamespace { public partial class MyMigration : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.Sql(""-- TEST"") .Annotation(""Some:EnumValue"", RegexOptions.Multiline); } protected override void Down(MigrationBuilder migrationBuilder) { } } } ", migrationCode); var migrationMetadataCode = generator.GenerateMetadata( "MyNamespace", typeof(MyContext), "MyMigration", "20150511161616_MyMigration", new Model {["Some:EnumValue"] = RegexOptions.Multiline }); Assert.Equal( @"using System; using Microsoft.Data.Entity; using Microsoft.Data.Entity.Infrastructure; using Microsoft.Data.Entity.Metadata; using Microsoft.Data.Entity.Migrations; using Microsoft.Data.Entity.Commands.Migrations; using System.Text.RegularExpressions; namespace MyNamespace { [DbContext(typeof(CodeCompilationTest.MyContext))] [Migration(""20150511161616_MyMigration"")] partial class MyMigration { protected override void BuildTargetModel(ModelBuilder modelBuilder) { modelBuilder .Annotation(""Some:EnumValue"", RegexOptions.Multiline); } } } ", migrationMetadataCode); var build = new BuildSource { References = { BuildReference.ByName(typeof(CodeCompilationTest).GetTypeInfo().Assembly.GetName().Name), #if DNXCORE50 BuildReference.ByName("System.Text.RegularExpressions"), #else BuildReference.ByName("System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"), BuildReference.ByName("System.Runtime, Version=4.0.10.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"), #endif BuildReference.ByName("EntityFramework.Core"), BuildReference.ByName("EntityFramework.Relational") }, Sources = { migrationCode, migrationMetadataCode } }; var assembly = build.BuildInMemory(); var migrationType = assembly.GetType("MyNamespace.MyMigration", throwOnError: true, ignoreCase: false); var contextTypeAttribute = migrationType.GetTypeInfo().GetCustomAttribute<DbContextAttribute>(); Assert.NotNull(contextTypeAttribute); Assert.Equal(typeof(MyContext), contextTypeAttribute.ContextType); var migration = (Migration)Activator.CreateInstance(migrationType); Assert.Equal("20150511161616_MyMigration", migration.GetId()); Assert.Equal(1, migration.UpOperations.Count); Assert.Empty(migration.DownOperations); Assert.Empty(migration.TargetModel.EntityTypes); }
public void Snapshots_compile() { var codeHelper = new CSharpHelper(); var generator = new CSharpMigrationGenerator( codeHelper, new CSharpMigrationOperationGenerator(codeHelper), new CSharpModelGenerator(codeHelper)); var modelSnapshotCode = generator.GenerateSnapshot("MyNamespace", typeof(MyContext), "MySnapshot", new Model()); Assert.Equal(@"using System; using Microsoft.Data.Entity; using Microsoft.Data.Entity.Metadata; using Microsoft.Data.Entity.Migrations.Infrastructure; using Microsoft.Data.Entity.Commands.Migrations; namespace MyNamespace { [ContextType(typeof(CodeCompilationTest.MyContext))] partial class MySnapshot : ModelSnapshot { public override void BuildModel(ModelBuilder builder) { } } } ", modelSnapshotCode); var build = new BuildSource { References = { BuildReference.ByName(typeof(CodeCompilationTest).Assembly.GetName().Name), BuildReference.ByName("System.Runtime, Version=4.0.10.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"), BuildReference.ByName("EntityFramework.Core"), BuildReference.ByName("EntityFramework.Relational") }, Sources = { modelSnapshotCode } }; var assembly = build.BuildInMemory(); var snapshotType = assembly.GetType("MyNamespace.MySnapshot", throwOnError: true); var contextTypeAttribute = snapshotType.GetCustomAttribute<ContextTypeAttribute>(); Assert.NotNull(contextTypeAttribute); Assert.Equal(typeof(MyContext), contextTypeAttribute.ContextType); var snapshot = (ModelSnapshot)Activator.CreateInstance(snapshotType); var conventions = new ConventionSet(); var modelBuilder = new ModelBuilder(conventions); snapshot.BuildModel(modelBuilder); Assert.Empty(modelBuilder.Model.EntityTypes); }
public CSharpMigrationOperationGenerator([NotNull] CSharpHelper code) { Check.NotNull(code, nameof(code)); _code = code; }
public void Migrations_compile() { var codeHelper = new CSharpHelper(); var generator = new CSharpMigrationGenerator( codeHelper, new CSharpMigrationOperationGenerator(codeHelper), new CSharpModelGenerator(codeHelper)); var migrationCode = generator.Generate( "MyNamespace", "MyMigration", new MigrationOperation[0], new MigrationOperation[0]); Assert.Equal( @"using System.Collections.Generic; using Microsoft.Data.Entity.Migrations; using Microsoft.Data.Entity.Migrations.Builders; using Microsoft.Data.Entity.Migrations.Operations; namespace MyNamespace { public partial class MyMigration : Migration { public override void Up(MigrationBuilder migration) { } public override void Down(MigrationBuilder migration) { } } } ", migrationCode); var migrationMetadataCode = generator.GenerateMetadata( "MyNamespace", typeof(MyContext), "MyMigration", "20150511161616_MyMigration", "7.0.0", new Model()); Assert.Equal( @"using System; using Microsoft.Data.Entity; using Microsoft.Data.Entity.Metadata; using Microsoft.Data.Entity.Migrations.Infrastructure; using Microsoft.Data.Entity.Commands.Migrations; namespace MyNamespace { [ContextType(typeof(CodeCompilationTest.MyContext))] partial class MyMigration { public override string Id { get { return ""20150511161616_MyMigration""; } } public override string ProductVersion { get { return ""7.0.0""; } } public override void BuildTargetModel(ModelBuilder builder) { } } } ", migrationMetadataCode); var build = new BuildSource { References = { BuildReference.ByName(typeof(CodeCompilationTest).Assembly.GetName().Name), BuildReference.ByName("System.Runtime, Version=4.0.10.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"), BuildReference.ByName("EntityFramework.Core"), BuildReference.ByName("EntityFramework.Relational") }, Sources = { migrationCode, migrationMetadataCode } }; var assembly = build.BuildInMemory(); var migrationType = assembly.GetType("MyNamespace.MyMigration", throwOnError: true); var contextTypeAttribute = migrationType.GetCustomAttribute<ContextTypeAttribute>(); Assert.NotNull(contextTypeAttribute); Assert.Equal(typeof(MyContext), contextTypeAttribute.ContextType); var migration = (Migration)Activator.CreateInstance(migrationType); Assert.Equal("20150511161616_MyMigration", migration.Id); Assert.Equal("7.0.0", migration.ProductVersion); var migrationBuilder = new MigrationBuilder(); migration.Up(migrationBuilder); Assert.Empty(migrationBuilder.Operations); migrationBuilder = new MigrationBuilder(); migration.Down(migrationBuilder); Assert.Empty(migrationBuilder.Operations); var conventions = new ConventionSet(); var modelBuilder = new ModelBuilder(conventions); migration.BuildTargetModel(modelBuilder); Assert.Empty(modelBuilder.Model.EntityTypes); }
public CSharpSnapshotGenerator([NotNull] CSharpHelper codeHelper) { Check.NotNull(codeHelper, nameof(codeHelper)); _code = codeHelper; }
public void Snapshots_compile() { var codeHelper = new CSharpHelper(); var generator = new CSharpMigrationsGenerator( codeHelper, new CSharpMigrationOperationGenerator(codeHelper), new CSharpSnapshotGenerator(codeHelper)); var modelSnapshotCode = generator.GenerateSnapshot( "MyNamespace", typeof(MyContext), "MySnapshot", new Model { ["Some:EnumValue"] = RegexOptions.Multiline }); Assert.Equal(@"using System; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Tools.Core.FunctionalTests.Migrations; using System.Text.RegularExpressions; namespace MyNamespace { [DbContext(typeof(CodeCompilationTest.MyContext))] partial class MySnapshot : ModelSnapshot { protected override void BuildModel(ModelBuilder modelBuilder) { modelBuilder .HasAnnotation(""Some:EnumValue"", RegexOptions.Multiline); } } } ", modelSnapshotCode); var snapshot = CompileModelSnapshot(modelSnapshotCode, "MyNamespace.MySnapshot"); Assert.Empty(snapshot.Model.GetEntityTypes()); }