Skip to content

Commit

Permalink
Discover the compiled model automatically
Browse files Browse the repository at this point in the history
Also add a way to manually reference the compiled model before it's generated

Tests tracked by #33136

Fixes #24893
  • Loading branch information
AndriySvyryd committed Feb 24, 2024
1 parent a2b8f2c commit 7bed44b
Show file tree
Hide file tree
Showing 67 changed files with 1,539 additions and 179 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ public class CSharpRuntimeModelCodeGenerator : ICompiledModelCodeGenerator
private readonly ICSharpRuntimeAnnotationCodeGenerator _annotationCodeGenerator;

private const string FileExtension = ".cs";
private const string AssemblyAttributesSuffix = "AssemblyAttributes";
private const string ModelSuffix = "Model";
private const string ModelBuilderSuffix = "ModelBuilder";
private const string EntityTypeSuffix = "EntityType";
Expand Down Expand Up @@ -62,6 +63,11 @@ public virtual IReadOnlyCollection<ScaffoldedFile> GenerateModel(
// Translated expressions don't have nullability annotations
var nullable = false;
var scaffoldedFiles = new List<ScaffoldedFile>();

var assemblyAttributesCode = CreateAssemblyAttributes(options.ModelNamespace, options.ContextType, nullable);
var assemblyInfoFileName = options.ContextType.ShortDisplayName() + AssemblyAttributesSuffix + FileExtension;
scaffoldedFiles.Add(new ScaffoldedFile { Path = assemblyInfoFileName, Code = assemblyAttributesCode });

var modelCode = CreateModel(options.ModelNamespace, options.ContextType, nullable);
var modelFileName = options.ContextType.ShortDisplayName() + ModelSuffix + FileExtension;
scaffoldedFiles.Add(new ScaffoldedFile { Path = modelFileName, Code = modelCode });
Expand Down Expand Up @@ -118,6 +124,29 @@ private static string GenerateHeader(SortedSet<string> namespaces, string curren
return builder.ToString();
}

private string CreateAssemblyAttributes(
string @namespace,
Type contextType,
bool nullable)
{
var mainBuilder = new IndentedStringBuilder();
var namespaces = new SortedSet<string>(new NamespaceComparer())
{
typeof(DbContextModelAttribute).Namespace!,
@namespace
};

AddNamespace(contextType, namespaces);

mainBuilder
.Append("[assembly: DbContextModel(typeof(").Append(_code.Reference(contextType))
.Append("), typeof(").Append(GetModelClassName(contextType)).AppendLine("))]");

return GenerateHeader(namespaces, currentNamespace: "", nullable) + mainBuilder;
}

private string GetModelClassName(Type contextType) => _code.Identifier(contextType.ShortDisplayName()) + ModelSuffix;

private string CreateModel(
string @namespace,
Type contextType,
Expand All @@ -139,7 +168,7 @@ private string CreateModel(
mainBuilder.Indent();
}

var className = _code.Identifier(contextType.ShortDisplayName()) + ModelSuffix;
var className = GetModelClassName(contextType);
mainBuilder
.Append("[DbContext(typeof(").Append(_code.Reference(contextType)).AppendLine("))]")
.Append("public partial class ").Append(className).AppendLine(" : " + nameof(RuntimeModel))
Expand Down Expand Up @@ -179,11 +208,14 @@ void RunInitialization()
.Append(" _instance = (")
.Append(className)
.AppendLine(")model.FinalizeModel();")
.AppendLine(" OnModelFinalized(_instance);")
.AppendLine("}")
.AppendLine()
.Append("private static ").Append(className).AppendLine(" _instance;")
.AppendLine("public static IModel Instance => _instance;")
.AppendLine()
.AppendLine("static partial void OnModelFinalized(IModel model);")
.AppendLine()
.AppendLine("partial void Initialize();")
.AppendLine()
.AppendLine("partial void Customize();");
Expand Down Expand Up @@ -222,7 +254,7 @@ private string CreateModelBuilder(
mainBuilder.Indent();
}

var className = _code.Identifier(contextType.ShortDisplayName()) + ModelSuffix;
var className = GetModelClassName(contextType);
mainBuilder
.Append("public partial class ").AppendLine(className)
.AppendLine("{");
Expand Down
42 changes: 42 additions & 0 deletions src/EFCore/Infrastructure/DbContextModelAttribute.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

namespace Microsoft.EntityFrameworkCore.Infrastructure;

/// <summary>
/// Identifies the <see cref="RuntimeModel" /> implementation that should be used for a given context.
/// </summary>
/// <remarks>
/// <para>
/// This attribute will usually be generated with the compiled model and doesn't need to be specified in your code.
/// </para>
/// <para>
/// See <see href="https://aka.ms/efcore-docs-dbcontext-pooling">Using DbContext pooling</see> for more information and examples.
/// </para>
/// </remarks>
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
public sealed class DbContextModelAttribute : Attribute
{
/// <summary>
/// Initializes a new instance of the <see cref="DbContextAttribute" /> class.
/// </summary>
/// <param name="contextType">The associated context.</param>
/// <param name="modelType">The compiled model.</param>
public DbContextModelAttribute(Type contextType, Type modelType)
{
Check.NotNull(contextType, nameof(contextType));

ContextType = contextType;
ModelType = modelType;
}

/// <summary>
/// Gets the associated context.
/// </summary>
public Type ContextType { get; }

/// <summary>
/// Gets the compiled model.
/// </summary>
public Type ModelType { get; }
}
36 changes: 34 additions & 2 deletions src/EFCore/Internal/DbContextServices.cs
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ private IModel CreateModel(bool designTime)
_inOnModelCreating = true;

var dependencies = _scopedProvider!.GetRequiredService<ModelCreationDependencies>();
var modelFromOptions = CoreOptions?.Model;
var modelFromOptions = CoreOptions?.Model ?? FindCompiledModel(_currentContext!.Context.GetType());

var modelVersion = modelFromOptions?.GetProductVersion();
if (modelVersion != null)
Expand All @@ -88,13 +88,45 @@ private IModel CreateModel(bool designTime)
|| (designTime && modelFromOptions is not Metadata.Internal.Model)
? RuntimeFeature.IsDynamicCodeSupported
? dependencies.ModelSource.GetModel(_currentContext!.Context, dependencies, designTime)
: throw new InvalidOperationException(CoreStrings.NativeAotNoCompiledModel)
: throw new InvalidOperationException(CoreStrings.NativeAotDesignTimeModel)
: dependencies.ModelRuntimeInitializer.Initialize(modelFromOptions, designTime, dependencies.ValidationLogger);
}
finally
{
_inOnModelCreating = false;
}

static IModel? FindCompiledModel(Type contextType)
{
var contextAssembly = contextType.Assembly;
IModel? model = null;
foreach (var modelAttribute in contextAssembly.GetCustomAttributes<DbContextModelAttribute>())
{
if (modelAttribute.ContextType != contextType)
{
continue;
}

var modelType = modelAttribute.ModelType;

var instanceProperty = modelType.GetProperty("Instance", BindingFlags.Public | BindingFlags.Static);
if (instanceProperty == null
|| instanceProperty.PropertyType != typeof(IModel))
{
throw new InvalidOperationException(CoreStrings.CompiledModelMissingInstance(modelType.DisplayName()));
}

if (model != null)
{
throw new InvalidOperationException(CoreStrings.CompiledModelDuplicateAttribute(
contextAssembly.FullName, contextType.DisplayName()));
}

model = (IModel)instanceProperty.GetValue(null)!;
}

return model;
}
}

/// <summary>
Expand Down
23 changes: 22 additions & 1 deletion src/EFCore/Properties/CoreStrings.Designer.cs

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

63 changes: 36 additions & 27 deletions src/EFCore/Properties/CoreStrings.resx
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
Expand All @@ -26,36 +26,36 @@
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
Expand Down Expand Up @@ -288,9 +288,15 @@
<data name="ComparerPropertyMismatchElement" xml:space="preserve">
<value>The comparer for element type '{type}' cannot be used for '{entityType}.{propertyName}' because its element type is '{elementType}'.</value>
</data>
<data name="CompiledModelDuplicateAttribute" xml:space="preserve">
<value>More than a single DbContextModelAttribute was found in the assembly '{assemblyName}' corresponding to the context type '{contextType}'</value>
</data>
<data name="CompiledModelIncompatibleTypeMapping" xml:space="preserve">
<value>The type mapping used is incompatible with a compiled model. The mapping type must have a 'public static readonly {typeMapping} {typeMapping}.Default' property.</value>
</data>
<data name="CompiledModelMissingInstance" xml:space="preserve">
<value>'{modelType}' must declare a static property named 'Instance' that returns 'IModel'.</value>
</data>
<data name="CompiledQueryDifferentModel" xml:space="preserve">
<value>The compiled query '{queryExpression}' was executed with a different model than it was compiled against. Compiled queries can only be used with a single model.</value>
</data>
Expand Down Expand Up @@ -1156,6 +1162,9 @@
<data name="NamedIndexWrongType" xml:space="preserve">
<value>The index with name {indexName} cannot be removed from the entity type '{entityType}' because no such index exists on that entity type.</value>
</data>
<data name="NativeAotDesignTimeModel" xml:space="preserve">
<value>Design-time DbContext operations are not supported when publishing with NativeAOT.</value>
</data>
<data name="NativeAotNoCompiledModel" xml:space="preserve">
<value>Model building is not supported when publishing with NativeAOT. Use a compiled model.</value>
</data>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
// <auto-generated />
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using TestNamespace;

#pragma warning disable 219, 612, 618
#nullable disable

[assembly: DbContextModel(typeof(DbContext), typeof(DbContextModel))]
Original file line number Diff line number Diff line change
Expand Up @@ -36,11 +36,14 @@ void RunInitialization()

model.Customize();
_instance = (DbContextModel)model.FinalizeModel();
OnModelFinalized(_instance);
}

private static DbContextModel _instance;
public static IModel Instance => _instance;

static partial void OnModelFinalized(IModel model);

partial void Initialize();

partial void Customize();
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
// <auto-generated />
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using TestNamespace;

#pragma warning disable 219, 612, 618
#nullable disable

[assembly: DbContextModel(typeof(DbContext), typeof(DbContextModel))]
Loading

0 comments on commit 7bed44b

Please sign in to comment.