-
Notifications
You must be signed in to change notification settings - Fork 3.1k
/
ModelBuilder.cs
583 lines (513 loc) · 27.4 KB
/
ModelBuilder.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using JetBrains.Annotations;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using Microsoft.EntityFrameworkCore.Metadata.Conventions;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using Microsoft.EntityFrameworkCore.Utilities;
namespace Microsoft.EntityFrameworkCore
{
/// <summary>
/// <para>
/// Provides a simple API surface for configuring a <see cref="IMutableModel" /> that defines the shape of your
/// entities, the relationships between them, and how they map to the database.
/// </para>
/// <para>
/// You can use <see cref="ModelBuilder" /> to construct a model for a context by overriding
/// <see cref="DbContext.OnModelCreating(ModelBuilder)" /> on your derived context. Alternatively you can create the
/// model externally and set it on a <see cref="DbContextOptions" /> instance that is passed to the context constructor.
/// </para>
/// </summary>
public class ModelBuilder : IInfrastructure<IConventionModelBuilder>
{
private readonly InternalModelBuilder _builder;
/// <summary>
/// Initializes a new instance of the <see cref="ModelBuilder" /> class that will
/// apply a set of conventions.
/// </summary>
/// <param name="conventions"> The conventions to be applied to the model. </param>
public ModelBuilder([NotNull] ConventionSet conventions)
: this(conventions, null, true)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ModelBuilder" /> class that will
/// apply a set of conventions.
/// </summary>
/// <param name="conventions"> The conventions to be applied to the model. </param>
/// <param name="modelDependencies"> The dependencies object for the model. </param>
public ModelBuilder([NotNull] ConventionSet conventions, [NotNull] ModelDependencies modelDependencies)
: this(conventions, modelDependencies, true)
{
Check.NotNull(modelDependencies, nameof(modelDependencies));
}
private ModelBuilder(ConventionSet conventions, ModelDependencies modelDependencies, bool _)
{
Check.NotNull(conventions, nameof(conventions));
_builder = new Model(conventions, modelDependencies).Builder;
_builder.Metadata.SetProductVersion(ProductInfo.GetVersion());
}
/// <summary>
/// <para>
/// Initializes a new instance of the <see cref="ModelBuilder" /> class with no conventions.
/// </para>
/// <para>
/// Warning: conventions are typically needed to build a correct model.
/// </para>
/// </summary>
public ModelBuilder()
{
_builder = new Model().Builder;
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
[Obsolete]
public ModelBuilder([NotNull] IMutableModel model)
{
Check.NotNull(model, nameof(model));
_builder = ((Model)model).Builder;
}
/// <summary>
/// The model being configured.
/// </summary>
public virtual IMutableModel Model
=> Builder.Metadata;
/// <summary>
/// Adds or updates an annotation on the model. If an annotation with the key specified in
/// <paramref name="annotation" /> already exists its value will be updated.
/// </summary>
/// <param name="annotation"> The key of the annotation to be added or updated. </param>
/// <param name="value"> The value to be stored in the annotation. </param>
/// <returns> The same <see cref="ModelBuilder" /> instance so that multiple configuration calls can be chained. </returns>
public virtual ModelBuilder HasAnnotation([NotNull] string annotation, [NotNull] object value)
{
Check.NotEmpty(annotation, nameof(annotation));
Check.NotNull(value, nameof(value));
Builder.HasAnnotation(annotation, value, ConfigurationSource.Explicit);
return this;
}
/// <summary>
/// <para>
/// The internal <see cref="ModelBuilder" /> being used to configure this model.
/// </para>
/// <para>
/// This property is intended for use by extension methods to configure the model. It is not intended to be used in
/// application code.
/// </para>
/// </summary>
IConventionModelBuilder IInfrastructure<IConventionModelBuilder>.Instance
=> _builder;
/// <summary>
/// Returns an object that can be used to configure a given entity type in the model.
/// If the entity type is not already part of the model, it will be added to the model.
/// </summary>
/// <typeparam name="TEntity"> The entity type to be configured. </typeparam>
/// <returns> An object that can be used to configure the entity type. </returns>
public virtual EntityTypeBuilder<TEntity> Entity<TEntity>()
where TEntity : class
=> new(Builder.Entity(typeof(TEntity), ConfigurationSource.Explicit).Metadata);
/// <summary>
/// <para>
/// Returns an object that can be used to configure a given shared type entity type in the model.
/// </para>
/// <para>
/// If an entity type with the provided name is not already part of the model, a new entity type with provided CLR
/// type will be added to the model as shared type entity type.
/// </para>
/// <para>
/// Shared type entity type is an entity type which can share CLR type with other types in the model but has
/// a unique name and always identified by the name.
/// </para>
/// </summary>
/// <typeparam name="TEntity"> The CLR type of the entity type to be configured. </typeparam>
/// <param name="name"> The name of the entity type to be configured. </param>
/// <returns> An object that can be used to configure the entity type. </returns>
public virtual EntityTypeBuilder<TEntity> SharedTypeEntity<TEntity>([NotNull] string name)
where TEntity : class
{
Check.NotEmpty(name, nameof(name));
return new EntityTypeBuilder<TEntity>(Builder.SharedTypeEntity(name, typeof(TEntity), ConfigurationSource.Explicit).Metadata);
}
/// <summary>
/// Returns an object that can be used to configure a given entity type in the model.
/// If the entity type is not already part of the model, it will be added to the model.
/// </summary>
/// <param name="type"> The entity type to be configured. </param>
/// <returns> An object that can be used to configure the entity type. </returns>
public virtual EntityTypeBuilder Entity([NotNull] Type type)
{
Check.NotNull(type, nameof(type));
return new EntityTypeBuilder(Builder.Entity(type, ConfigurationSource.Explicit).Metadata);
}
/// <summary>
/// Returns an object that can be used to configure a given entity type in the model.
/// If an entity type with the provided name is not already part of the model,
/// a new entity type that does not have a corresponding CLR type will be added to the model.
/// </summary>
/// <param name="name"> The name of the entity type to be configured. </param>
/// <returns> An object that can be used to configure the entity type. </returns>
public virtual EntityTypeBuilder Entity([NotNull] string name)
{
Check.NotEmpty(name, nameof(name));
return new EntityTypeBuilder(Builder.Entity(name, ConfigurationSource.Explicit).Metadata);
}
/// <summary>
/// <para>
/// Returns an object that can be used to configure a given shared type entity type in the model.
/// </para>
/// <para>
/// If an entity type with the provided name is not already part of the model, a new entity type with provided CLR
/// type will be added to the model as shared type entity type.
/// </para>
/// <para>
/// Shared type entity type is an entity type which can share CLR type with other types in the model but has
/// a unique name and always identified by the name.
/// </para>
/// </summary>
/// <param name="name"> The name of the entity type to be configured. </param>
/// <param name="type"> The CLR type of the entity type to be configured. </param>
/// <returns> An object that can be used to configure the entity type. </returns>
public virtual EntityTypeBuilder SharedTypeEntity([NotNull] string name, [NotNull] Type type)
{
Check.NotEmpty(name, nameof(name));
Check.NotNull(type, nameof(type));
return new EntityTypeBuilder(Builder.SharedTypeEntity(name, type, ConfigurationSource.Explicit).Metadata);
}
/// <summary>
/// <para>
/// Performs configuration of a given entity type in the model. If the entity type is not already part
/// of the model, it will be added to the model.
/// </para>
/// <para>
/// This overload allows configuration of the entity type to be done in line in the method call rather
/// than being chained after a call to <see cref="Entity{TEntity}()" />. This allows additional
/// configuration at the model level to be chained after configuration for the entity type.
/// </para>
/// </summary>
/// <typeparam name="TEntity"> The entity type to be configured. </typeparam>
/// <param name="buildAction"> An action that performs configuration of the entity type. </param>
/// <returns>
/// The same <see cref="ModelBuilder" /> instance so that additional configuration calls can be chained.
/// </returns>
public virtual ModelBuilder Entity<TEntity>([NotNull] Action<EntityTypeBuilder<TEntity>> buildAction)
where TEntity : class
{
Check.NotNull(buildAction, nameof(buildAction));
buildAction(Entity<TEntity>());
return this;
}
/// <summary>
/// <para>
/// Returns an object that can be used to configure a given shared type entity type in the model.
/// </para>
/// <para>
/// If an entity type with the provided name is not already part of the model, a new entity type with provided CLR
/// type will be added to the model as shared type entity type.
/// </para>
/// <para>
/// Shared type entity type is an entity type which can share CLR type with other types in the model but has
/// a unique name and always identified by the name.
/// </para>
/// <para>
/// This overload allows configuration of the entity type to be done inline in the method call rather
/// than being chained after a call to <see cref="Entity{TEntity}()" />. This allows additional
/// configuration at the model level to be chained after configuration for the entity type.
/// </para>
/// </summary>
/// <typeparam name="TEntity"> The CLR type of the entity type to be configured. </typeparam>
/// <param name="name"> The name of the entity type to be configured. </param>
/// <param name="buildAction"> An action that performs configuration of the entity type. </param>
/// <returns>
/// The same <see cref="ModelBuilder" /> instance so that additional configuration calls can be chained.
/// </returns>
public virtual ModelBuilder SharedTypeEntity<TEntity>(
[NotNull] string name,
[NotNull] Action<EntityTypeBuilder<TEntity>> buildAction)
where TEntity : class
{
Check.NotEmpty(name, nameof(name));
Check.NotNull(buildAction, nameof(buildAction));
buildAction(SharedTypeEntity<TEntity>(name));
return this;
}
/// <summary>
/// <para>
/// Performs configuration of a given entity type in the model. If the entity type is not already part
/// of the model, it will be added to the model.
/// </para>
/// <para>
/// This overload allows configuration of the entity type to be done in line in the method call rather
/// than being chained after a call to <see cref="Entity{TEntity}()" />. This allows additional
/// configuration at the model level to be chained after configuration for the entity type.
/// </para>
/// </summary>
/// <param name="type"> The entity type to be configured. </param>
/// <param name="buildAction"> An action that performs configuration of the entity type. </param>
/// <returns>
/// The same <see cref="ModelBuilder" /> instance so that additional configuration calls can be chained.
/// </returns>
public virtual ModelBuilder Entity([NotNull] Type type, [NotNull] Action<EntityTypeBuilder> buildAction)
{
Check.NotNull(type, nameof(type));
Check.NotNull(buildAction, nameof(buildAction));
buildAction(Entity(type));
return this;
}
/// <summary>
/// <para>
/// Performs configuration of a given entity type in the model.
/// If an entity type with the provided name is not already part of the model,
/// a new entity type that does not have a corresponding CLR type will be added to the model.
/// </para>
/// <para>
/// This overload allows configuration of the entity type to be done in line in the method call rather
/// than being chained after a call to <see cref="Entity(string)" />. This allows additional
/// configuration at the model level to be chained after configuration for the entity type.
/// </para>
/// </summary>
/// <param name="name"> The name of the entity type to be configured. </param>
/// <param name="buildAction"> An action that performs configuration of the entity type. </param>
/// <returns>
/// The same <see cref="ModelBuilder" /> instance so that additional configuration calls can be chained.
/// </returns>
public virtual ModelBuilder Entity([NotNull] string name, [NotNull] Action<EntityTypeBuilder> buildAction)
{
Check.NotEmpty(name, nameof(name));
Check.NotNull(buildAction, nameof(buildAction));
buildAction(Entity(name));
return this;
}
/// <summary>
/// <para>
/// Returns an object that can be used to configure a given shared type entity type in the model.
/// </para>
/// <para>
/// If an entity type with the provided name is not already part of the model, a new entity type with provided CLR
/// type will be added to the model as shared type entity type.
/// </para>
/// <para>
/// Shared type entity type is an entity type which can share CLR type with other types in the model but has
/// a unique name and always identified by the name.
/// </para>
/// <para>
/// This overload allows configuration of the entity type to be done in line in the method call rather
/// than being chained after a call to <see cref="Entity(string)" />. This allows additional
/// configuration at the model level to be chained after configuration for the entity type.
/// </para>
/// </summary>
/// <param name="name"> The name of the entity type to be configured. </param>
/// <param name="type"> The CLR type of the entity type to be configured. </param>
/// <param name="buildAction"> An action that performs configuration of the entity type. </param>
/// <returns>
/// The same <see cref="ModelBuilder" /> instance so that additional configuration calls can be chained.
/// </returns>
public virtual ModelBuilder SharedTypeEntity(
[NotNull] string name,
[NotNull] Type type,
[NotNull] Action<EntityTypeBuilder> buildAction)
{
Check.NotEmpty(name, nameof(name));
Check.NotNull(type, nameof(type));
Check.NotNull(buildAction, nameof(buildAction));
buildAction(SharedTypeEntity(name, type));
return this;
}
/// <summary>
/// Excludes the given entity type from the model. This method is typically used to remove types from
/// the model that were added by convention.
/// </summary>
/// <typeparam name="TEntity"> The entity type to be removed from the model. </typeparam>
/// <returns>
/// The same <see cref="ModelBuilder" /> instance so that additional configuration calls can be chained.
/// </returns>
public virtual ModelBuilder Ignore<TEntity>()
where TEntity : class
=> Ignore(typeof(TEntity));
/// <summary>
/// Excludes an entity type with given CLR type from the model. This method is typically used to remove types from
/// the model that were added by convention.
/// </summary>
/// <param name="type"> The entity type to be removed from the model. </param>
/// <returns>
/// The same <see cref="ModelBuilder" /> instance so that additional configuration calls can be chained.
/// </returns>
public virtual ModelBuilder Ignore([NotNull] Type type)
{
Check.NotNull(type, nameof(type));
Builder.Ignore(type, ConfigurationSource.Explicit);
return this;
}
/// <summary>
/// Excludes an entity type with the given name from the model. This method is typically used to remove types from
/// the model that were added by convention.
/// </summary>
/// <param name="typeName"> The name of the entity type to be removed from the model. </param>
/// <returns>
/// The same <see cref="ModelBuilder" /> instance so that additional configuration calls can be chained.
/// </returns>
public virtual ModelBuilder Ignore([NotNull] string typeName)
{
Check.NotEmpty(typeName, nameof(typeName));
Builder.Ignore(typeName, ConfigurationSource.Explicit);
return this;
}
/// <summary>
/// Applies configuration that is defined in an <see cref="IEntityTypeConfiguration{TEntity}" /> instance.
/// </summary>
/// <typeparam name="TEntity"> The entity type to be configured. </typeparam>
/// <param name="configuration"> The configuration to be applied. </param>
/// <returns>
/// The same <see cref="ModelBuilder" /> instance so that additional configuration calls can be chained.
/// </returns>
public virtual ModelBuilder ApplyConfiguration<TEntity>([NotNull] IEntityTypeConfiguration<TEntity> configuration)
where TEntity : class
{
Check.NotNull(configuration, nameof(configuration));
configuration.Configure(Entity<TEntity>());
return this;
}
/// <summary>
/// Applies configuration from all <see cref="IEntityTypeConfiguration{TEntity}" /> />
/// instances that are defined in provided assembly.
/// </summary>
/// <param name="assembly"> The assembly to scan. </param>
/// <param name="predicate"> Optional predicate to filter types within the assembly. </param>
/// <returns>
/// The same <see cref="ModelBuilder" /> instance so that additional configuration calls can be chained.
/// </returns>
public virtual ModelBuilder ApplyConfigurationsFromAssembly(
[NotNull] Assembly assembly,
[CanBeNull] Func<Type, bool> predicate = null)
{
var applyEntityConfigurationMethod = typeof(ModelBuilder)
.GetMethods()
.Single(
e => e.Name == nameof(ApplyConfiguration)
&& e.ContainsGenericParameters
&& e.GetParameters().SingleOrDefault()?.ParameterType.GetGenericTypeDefinition()
== typeof(IEntityTypeConfiguration<>));
foreach (var type in assembly.GetConstructibleTypes())
{
// Only accept types that contain a parameterless constructor, are not abstract and satisfy a predicate if it was used.
if (type.GetConstructor(Type.EmptyTypes) == null
|| (!predicate?.Invoke(type) ?? false))
{
continue;
}
foreach (var @interface in type.GetInterfaces())
{
if (!@interface.IsGenericType)
{
continue;
}
if (@interface.GetGenericTypeDefinition() == typeof(IEntityTypeConfiguration<>))
{
var target = applyEntityConfigurationMethod.MakeGenericMethod(@interface.GenericTypeArguments[0]);
target.Invoke(this, new[] { Activator.CreateInstance(type) });
}
}
}
return this;
}
/// <summary>
/// Marks an entity type as owned. All references to this type will be configured as
/// separate owned type instances.
/// </summary>
/// <typeparam name="T"> The entity type to be configured. </typeparam>
public virtual OwnedEntityTypeBuilder<T> Owned<T>()
where T : class
{
Builder.Owned(typeof(T), ConfigurationSource.Explicit);
return new OwnedEntityTypeBuilder<T>();
}
/// <summary>
/// Marks an entity type as owned. All references to this type will be configured as
/// separate owned type instances.
/// </summary>
/// <param name="type"> The entity type to be configured. </param>
public virtual OwnedEntityTypeBuilder Owned([NotNull] Type type)
{
Check.NotNull(type, nameof(type));
Builder.Owned(type, ConfigurationSource.Explicit);
return new OwnedEntityTypeBuilder();
}
/// <summary>
/// Configures the default <see cref="ChangeTrackingStrategy" /> to be used for this model.
/// This strategy indicates how the context detects changes to properties for an instance of an entity type.
/// </summary>
/// <param name="changeTrackingStrategy"> The change tracking strategy to be used. </param>
/// <returns>
/// The same <see cref="ModelBuilder" /> instance so that additional configuration calls can be chained.
/// </returns>
public virtual ModelBuilder HasChangeTrackingStrategy(ChangeTrackingStrategy changeTrackingStrategy)
{
Builder.Metadata.SetChangeTrackingStrategy(changeTrackingStrategy);
return this;
}
/// <summary>
/// <para>
/// Sets the <see cref="PropertyAccessMode" /> to use for all properties of this entity type.
/// </para>
/// <para>
/// By default, the backing field, if one is found by convention or has been specified, is used when
/// new objects are constructed, typically when entities are queried from the database.
/// Properties are used for all other accesses. Calling this method will change that behavior
/// for all properties in the model as described in the <see cref="PropertyAccessMode" /> enum.
/// </para>
/// </summary>
/// <param name="propertyAccessMode"> The <see cref="PropertyAccessMode" /> to use for properties of this model. </param>
/// <returns>
/// The same <see cref="ModelBuilder" /> instance so that additional configuration calls can be chained.
/// </returns>
public virtual ModelBuilder UsePropertyAccessMode(PropertyAccessMode propertyAccessMode)
{
Builder.UsePropertyAccessMode(propertyAccessMode, ConfigurationSource.Explicit);
return this;
}
/// <summary>
/// Forces post-processing on the model such that it is ready for use by the runtime. This post
/// processing happens automatically when using <see cref="DbContext.OnModelCreating" />; this method allows it to be run
/// explicitly in cases where the automatic execution is not possible.
/// </summary>
/// <returns> The finalized model. </returns>
public virtual IModel FinalizeModel()
=> Builder.Metadata.FinalizeModel();
private InternalModelBuilder Builder
=> (InternalModelBuilder)this.GetInfrastructure();
#region Hidden System.Object members
/// <summary>
/// Returns a string that represents the current object.
/// </summary>
/// <returns> A string that represents the current object. </returns>
[EditorBrowsable(EditorBrowsableState.Never)]
public override string ToString()
=> base.ToString();
/// <summary>
/// Determines whether the specified object is equal to the current object.
/// </summary>
/// <param name="obj"> The object to compare with the current object. </param>
/// <returns> <see langword="true" /> if the specified object is equal to the current object; otherwise, <see langword="false" />. </returns>
[EditorBrowsable(EditorBrowsableState.Never)]
public override bool Equals(object obj)
=> base.Equals(obj);
/// <summary>
/// Serves as the default hash function.
/// </summary>
/// <returns> A hash code for the current object. </returns>
[EditorBrowsable(EditorBrowsableState.Never)]
public override int GetHashCode()
=> base.GetHashCode();
#endregion
}
}