language
stringclasses
1 value
repo
stringclasses
133 values
path
stringlengths
13
229
class_span
dict
source
stringlengths
14
2.92M
target
stringlengths
1
153
csharp
unoplatform__uno
src/SamplesApp/UITests.Shared/Microsoft_UI_Windowing/AppWindowTitleBarProperties.xaml.cs
{ "start": 413, "end": 542 }
partial class ____ : Page { public AppWindowTitleBarProperties() { this.InitializeComponent(); } }
AppWindowTitleBarProperties
csharp
mongodb__mongo-csharp-driver
tests/MongoDB.Driver.Tests/Linq/Linq3Implementation/Jira/CSharp4317Tests.cs
{ "start": 865, "end": 1828 }
public class ____ : LinqIntegrationTest<CSharp4317Tests.ClassFixture> { public CSharp4317Tests(ClassFixture fixture) : base(fixture) { } [Fact] public void Projection_of_ArrayOfDocuments_dictionary_keys_and_values_should_work() { var collection = Fixture.Collection; var projectStage = "{ $project : { Keys : '$Data.k', Values : '$Data.v', _id : 0 } }"; var queryable = collection .AsQueryable() .Select(x => new { Keys = x.Data.Select(y => y.Key), Values = x.Data.Select(y => y.Value) }); var stages = Translate(collection, queryable); AssertStages(stages, projectStage); var result = queryable.First(); result.Keys.Should().Equal(1, 2); result.Values.Should().Equal("v1", "v2"); }
CSharp4317Tests
csharp
abpframework__abp
framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/ProjectBuilding/ProjectBuildArgs.cs
{ "start": 151, "end": 3102 }
public class ____ { [NotNull] public SolutionName SolutionName { get; } [CanBeNull] public string TemplateName { get; set; } [CanBeNull] public string Version { get; set; } public bool TrustUserVersion { get; set; } public DatabaseProvider DatabaseProvider { get; set; } public DatabaseManagementSystem DatabaseManagementSystem { get; set; } public UiFramework UiFramework { get; set; } public MobileApp? MobileApp { get; set; } public bool PublicWebSite { get; set; } [CanBeNull] public string AbpGitHubLocalRepositoryPath { get; set; } [CanBeNull] public string VoloGitHubLocalRepositoryPath { get; set; } [CanBeNull] public string TemplateSource { get; set; } [CanBeNull] public string ConnectionString { get; set; } [NotNull] public string OutputFolder { get; set; } public bool Pwa { get; set; } public Theme? Theme { get; set; } public ThemeStyle? ThemeStyle { get; set; } public bool SkipCache { get; set; } [NotNull] public Dictionary<string, string> ExtraProperties { get; set; } public ProjectBuildArgs( [NotNull] SolutionName solutionName, [CanBeNull] string templateName = null, [CanBeNull] string version = null, string outputFolder = null, DatabaseProvider databaseProvider = DatabaseProvider.NotSpecified, DatabaseManagementSystem databaseManagementSystem = DatabaseManagementSystem.NotSpecified, UiFramework uiFramework = UiFramework.NotSpecified, MobileApp? mobileApp = null, bool publicWebSite = false, [CanBeNull] string abpGitHubLocalRepositoryPath = null, [CanBeNull] string voloGitHubLocalRepositoryPath = null, [CanBeNull] string templateSource = null, Dictionary<string, string> extraProperties = null, [CanBeNull] string connectionString = null, bool pwa = false, Theme? theme = null, ThemeStyle? themeStyle = null, bool skipCache = false, bool trustUserVersion = false) { SolutionName = Check.NotNull(solutionName, nameof(solutionName)); TemplateName = templateName; Version = version; OutputFolder = outputFolder; DatabaseProvider = databaseProvider; DatabaseManagementSystem = databaseManagementSystem; UiFramework = uiFramework; MobileApp = mobileApp; PublicWebSite = publicWebSite; AbpGitHubLocalRepositoryPath = abpGitHubLocalRepositoryPath; VoloGitHubLocalRepositoryPath = voloGitHubLocalRepositoryPath; TemplateSource = templateSource; ExtraProperties = extraProperties ?? new Dictionary<string, string>(); ConnectionString = connectionString; Pwa = pwa; Theme = theme; ThemeStyle = themeStyle; SkipCache = skipCache; TrustUserVersion = trustUserVersion; } }
ProjectBuildArgs
csharp
dotnet__orleans
src/api/Orleans.Journaling/Orleans.Journaling.cs
{ "start": 4022, "end": 4437 }
public partial interface ____ { void AppendEntries(StateMachineStorageWriter writer); void AppendSnapshot(StateMachineStorageWriter writer); void Apply(System.Buffers.ReadOnlySequence<byte> entry); IDurableStateMachine DeepCopy(); void OnRecoveryCompleted(); void OnWriteCompleted(); void Reset(IStateMachineLogWriter storage); }
IDurableStateMachine
csharp
RicoSuter__NSwag
src/NSwag.CodeGeneration.CSharp.Tests/ControllerGenerationFormatTests.cs
{ "start": 16656, "end": 16830 }
public class ____ :").Count; Assert.Equal(1, fromHeaderCustomAttributeCount); var fromHeaderCustomBindingCount = Regex.Matches(code, "
FromHeaderAttribute
csharp
MapsterMapper__Mapster
src/Mapster.Async.Tests/AsyncTest.cs
{ "start": 4594, "end": 4749 }
public class ____ { public string Id { get; set; } public string Make { get; set; } public string Model { get; set; } } }
DoCar
csharp
dotnetcore__WTM
src/WalkingTec.Mvvm.TagHelpers.LayUI/FlowInfoTagHelper.cs
{ "start": 322, "end": 1461 }
public class ____ : BaseElementTag { public ModelExpression Vm { get; set; } public override void Process(TagHelperContext context, TagHelperOutput output) { List<ApproveTimeLine> data = new List<ApproveTimeLine>(); if (Vm?.Model is IBaseCRUDVM<TopBasePoco> vm) { data = vm.GetWorkflowTimeLineAsync().Result; } output.TagName = "ul"; output.TagMode = TagMode.StartTagAndEndTag; output.Attributes.SetAttribute("class", "layui-timeline"); foreach (var item in data) { output.Content.AppendHtml($@" <li class=""layui-timeline-item""> <i class=""layui-icon layui-timeline-axis"">&#xe63f;</i> <div class=""layui-timeline-content layui-text""> <h3 class=""layui-timeline-title"">{item.Time}</h3> <p> {item.Message} </p> <p>{(string.IsNullOrEmpty(item.Remark) ? "": "备注:" + item.Remark)}</p> </div> </li> "); } base.Process(context, output); } } }
FlowInfoTagHelper
csharp
Testably__Testably.Abstractions
Source/Testably.Abstractions.Testing/TimeSystem/NotificationHandler.cs
{ "start": 69, "end": 1788 }
internal sealed class ____ : INotificationHandler { private readonly Notification.INotificationFactory<DateTime> _dateTimeReadCallbacks = Notification.CreateFactory<DateTime>(); private readonly Notification.INotificationFactory<TimeSpan> _taskDelayCallbacks = Notification.CreateFactory<TimeSpan>(); private readonly Notification.INotificationFactory<TimeSpan> _threadSleepCallbacks = Notification.CreateFactory<TimeSpan>(); #region INotificationHandler Members /// <inheritdoc cref="INotificationHandler.DateTimeRead(Action{DateTime}?, Func{DateTime, bool}?)" /> public IAwaitableCallback<DateTime> DateTimeRead( Action<DateTime>? callback = null, Func<DateTime, bool>? predicate = null) => _dateTimeReadCallbacks.RegisterCallback(callback, predicate); /// <inheritdoc cref="INotificationHandler.TaskDelay(Action{TimeSpan}?, Func{TimeSpan, bool}?)" /> public IAwaitableCallback<TimeSpan> TaskDelay( Action<TimeSpan>? callback = null, Func<TimeSpan, bool>? predicate = null) => _taskDelayCallbacks.RegisterCallback(callback, predicate); /// <inheritdoc cref="INotificationHandler.ThreadSleep(Action{TimeSpan}?, Func{TimeSpan, bool}?)" /> public IAwaitableCallback<TimeSpan> ThreadSleep( Action<TimeSpan>? callback = null, Func<TimeSpan, bool>? predicate = null) => _threadSleepCallbacks.RegisterCallback(callback, predicate); #endregion public void InvokeDateTimeReadCallbacks(DateTime now) => _dateTimeReadCallbacks.InvokeCallbacks(now); public void InvokeTaskDelayCallbacks(TimeSpan delay) => _taskDelayCallbacks.InvokeCallbacks(delay); public void InvokeThreadSleepCallbacks(TimeSpan timeout) => _threadSleepCallbacks.InvokeCallbacks(timeout); }
NotificationHandler
csharp
dotnet__orleans
test/Tester/DuplicateActivationsTests.cs
{ "start": 777, "end": 924 }
public class ____ : IClassFixture<DuplicateActivationsTests.Fixture> { private readonly Fixture fixture;
DuplicateActivationsTests
csharp
graphql-dotnet__graphql-dotnet
src/GraphQL.MicrosoftDI/ResolverBuilder.cs
{ "start": 19939, "end": 24303 }
public class ____<TSourceType, TReturnType, T1, T2, T3, T4, T5> { private readonly FieldBuilder<TSourceType, TReturnType> _builder; private bool _scoped; /// <inheritdoc cref="ResolverBuilder{TSourceType, TReturnType}(FieldBuilder{TSourceType, TReturnType}, bool)"/> public ResolverBuilder(FieldBuilder<TSourceType, TReturnType> builder, bool scoped) { _builder = builder; _scoped = scoped; } /// <inheritdoc cref="ResolverBuilder{TSourceType, TReturnType}.WithScope"/> public ResolverBuilder<TSourceType, TReturnType, T1, T2, T3, T4, T5> WithScope() { _scoped = true; return this; } /// <inheritdoc cref="ResolverBuilder{TSourceType, TReturnType}.Resolve(Func{IResolveFieldContext{TSourceType}, TReturnType})"/> public FieldBuilder<TSourceType, TReturnType> Resolve(Func<IResolveFieldContext<TSourceType>, T1, T2, T3, T4, T5, TReturnType?> resolver) { Func<IResolveFieldContext<TSourceType>, TReturnType?> resolver2 = context => resolver( context, context.RequestServices.GetRequiredService<T1>(), context.RequestServices.GetRequiredService<T2>(), context.RequestServices.GetRequiredService<T3>(), context.RequestServices.GetRequiredService<T4>(), context.RequestServices.GetRequiredService<T5>()); _builder.FieldType.DependsOn(typeof(T1)); _builder.FieldType.DependsOn(typeof(T2)); _builder.FieldType.DependsOn(typeof(T3)); _builder.FieldType.DependsOn(typeof(T4)); _builder.FieldType.DependsOn(typeof(T5)); return _scoped ? _builder.ResolveScoped(resolver2) : _builder.Resolve(resolver2); } /// <inheritdoc cref="ResolverBuilder{TSourceType, TReturnType}.ResolveAsync(Func{IResolveFieldContext{TSourceType}, Task{TReturnType}})"/> public FieldBuilder<TSourceType, TReturnType> ResolveAsync(Func<IResolveFieldContext<TSourceType>, T1, T2, T3, T4, T5, Task<TReturnType?>> resolver) { Func<IResolveFieldContext<TSourceType>, Task<TReturnType?>> resolver2 = context => resolver( context, context.RequestServices.GetRequiredService<T1>(), context.RequestServices.GetRequiredService<T2>(), context.RequestServices.GetRequiredService<T3>(), context.RequestServices.GetRequiredService<T4>(), context.RequestServices.GetRequiredService<T5>()); _builder.FieldType.DependsOn(typeof(T1)); _builder.FieldType.DependsOn(typeof(T2)); _builder.FieldType.DependsOn(typeof(T3)); _builder.FieldType.DependsOn(typeof(T4)); _builder.FieldType.DependsOn(typeof(T5)); return _scoped ? _builder.ResolveScopedAsync(resolver2) : _builder.ResolveAsync(resolver2); } private ResolverBuilder<TSourceType, IDataLoaderResult<TReturnType>, T1, T2, T3, T4, T5> ReturnsDataLoader() => new(_builder.ReturnsDataLoader(), _scoped); /// <inheritdoc cref="ResolverBuilder{TSourceType, TReturnType}.ResolveAsync(Func{IResolveFieldContext{TSourceType}, Task{TReturnType}})"/> public FieldBuilder<TSourceType, TReturnType> ResolveAsync(Func<IResolveFieldContext<TSourceType>, T1, T2, T3, T4, T5, IDataLoaderResult<TReturnType>?> resolver) { ReturnsDataLoader().Resolve(resolver); return _builder; } /// <inheritdoc cref="ResolverBuilder{TSourceType, TReturnType}.ResolveAsync(Func{IResolveFieldContext{TSourceType}, Task{TReturnType}})"/> public FieldBuilder<TSourceType, TReturnType> ResolveAsync(Func<IResolveFieldContext<TSourceType>, T1, T2, T3, T4, T5, IDataLoaderResult<IDataLoaderResult<TReturnType>>?> resolver) { ReturnsDataLoader().ReturnsDataLoader().Resolve(resolver); return _builder; } /// <inheritdoc cref="ResolverBuilder{TSourceType, TReturnType}.ResolveAsync(Func{IResolveFieldContext{TSourceType}, Task{TReturnType}})"/> public FieldBuilder<TSourceType, TReturnType> ResolveAsync(Func<IResolveFieldContext<TSourceType>, T1, T2, T3, T4, T5, IDataLoaderResult<IDataLoaderResult<IDataLoaderResult<TReturnType>>>?> resolver) { ReturnsDataLoader().ReturnsDataLoader().ReturnsDataLoader().Resolve(resolver); return _builder; } }
ResolverBuilder
csharp
LibreHardwareMonitor__LibreHardwareMonitor
LibreHardwareMonitorLib/Hardware/Gpu/NvidiaGroup.cs
{ "start": 538, "end": 3586 }
internal class ____ : IGroup { private readonly List<Hardware> _hardware = new(); private readonly StringBuilder _report = new(); public NvidiaGroup(ISettings settings) { NvApi.Initialize(); if (!NvApi.IsAvailable) return; _report.AppendLine("NvApi"); _report.AppendLine(); if (NvApi.NvAPI_GetInterfaceVersionString(out string version) == NvApi.NvStatus.OK) { _report.Append("Version: "); _report.AppendLine(version); } NvApi.NvPhysicalGpuHandle[] handles = new NvApi.NvPhysicalGpuHandle[NvApi.MAX_PHYSICAL_GPUS]; if (NvApi.NvAPI_EnumPhysicalGPUs == null) { _report.AppendLine("Error: NvAPI_EnumPhysicalGPUs not available"); _report.AppendLine(); return; } NvApi.NvStatus status = NvApi.NvAPI_EnumPhysicalGPUs(handles, out int count); if (status != NvApi.NvStatus.OK) { _report.AppendLine("Status: " + status); _report.AppendLine(); return; } IDictionary<NvApi.NvPhysicalGpuHandle, NvApi.NvDisplayHandle> displayHandles = new Dictionary<NvApi.NvPhysicalGpuHandle, NvApi.NvDisplayHandle>(); if (NvApi.NvAPI_EnumNvidiaDisplayHandle != null && NvApi.NvAPI_GetPhysicalGPUsFromDisplay != null) { status = NvApi.NvStatus.OK; int i = 0; while (status == NvApi.NvStatus.OK) { NvApi.NvDisplayHandle displayHandle = new(); status = NvApi.NvAPI_EnumNvidiaDisplayHandle(i, ref displayHandle); i++; if (status == NvApi.NvStatus.OK) { NvApi.NvPhysicalGpuHandle[] handlesFromDisplay = new NvApi.NvPhysicalGpuHandle[NvApi.MAX_PHYSICAL_GPUS]; if (NvApi.NvAPI_GetPhysicalGPUsFromDisplay(displayHandle, handlesFromDisplay, out uint countFromDisplay) == NvApi.NvStatus.OK) { for (int j = 0; j < countFromDisplay; j++) { if (!displayHandles.ContainsKey(handlesFromDisplay[j])) displayHandles.Add(handlesFromDisplay[j], displayHandle); } } } } } _report.Append("Number of GPUs: "); _report.AppendLine(count.ToString(CultureInfo.InvariantCulture)); for (int i = 0; i < count; i++) { displayHandles.TryGetValue(handles[i], out NvApi.NvDisplayHandle displayHandle); _hardware.Add(new NvidiaGpu(i, handles[i], displayHandle, settings)); } _report.AppendLine(); } public IReadOnlyList<IHardware> Hardware => _hardware; public string GetReport() { return _report.ToString(); } public void Close() { foreach (Hardware gpu in _hardware) gpu.Close(); NvidiaML.Close(); } }
NvidiaGroup
csharp
microsoft__PowerToys
src/modules/MouseUtils/MouseJump.Common/Models/Styles/MarginStyle.cs
{ "start": 311, "end": 1296 }
public sealed class ____ { public static readonly MarginStyle Empty = new(0); public MarginStyle(decimal all) : this(all, all, all, all) { } public MarginStyle(decimal left, decimal top, decimal right, decimal bottom) { this.Left = left; this.Top = top; this.Right = right; this.Bottom = bottom; } public decimal Left { get; } public decimal Top { get; } public decimal Right { get; } public decimal Bottom { get; } public decimal Horizontal => this.Left + this.Right; public decimal Vertical => this.Top + this.Bottom; public override string ToString() { return "{" + $"{nameof(this.Left)}={this.Left}," + $"{nameof(this.Top)}={this.Top}," + $"{nameof(this.Right)}={this.Right}," + $"{nameof(this.Bottom)}={this.Bottom}" + "}"; } }
MarginStyle
csharp
AvaloniaUI__Avalonia
src/Avalonia.Controls/Utils/BorderRenderHelper.cs
{ "start": 265, "end": 5819 }
internal class ____ { private bool _useComplexRendering; private bool? _backendSupportsIndividualCorners; private Geometry? _backgroundGeometryCache; private Geometry? _borderGeometryCache; private Size _size; private Thickness _borderThickness; private CornerRadius _cornerRadius; private BackgroundSizing _backgroundSizing; private bool _initialized; private IPen? _cachedPen; private void Update(Size finalSize, Thickness borderThickness, CornerRadius cornerRadius, BackgroundSizing backgroundSizing) { _backendSupportsIndividualCorners ??= AvaloniaLocator.Current.GetRequiredService<IPlatformRenderInterface>() .SupportsIndividualRoundRects; _size = finalSize; _borderThickness = borderThickness; _cornerRadius = cornerRadius; _backgroundSizing = backgroundSizing; _initialized = true; if (borderThickness.IsUniform && (cornerRadius.IsUniform || _backendSupportsIndividualCorners == true) && backgroundSizing == BackgroundSizing.CenterBorder) { _backgroundGeometryCache = null; _borderGeometryCache = null; _useComplexRendering = false; } else { _useComplexRendering = true; var boundRect = new Rect(finalSize); var innerRect = boundRect.Deflate(borderThickness); if (innerRect.Width != 0 && innerRect.Height != 0) { var backgroundOuterKeypoints = GeometryBuilder.CalculateRoundedCornersRectangleWinUI( boundRect, borderThickness, cornerRadius, backgroundSizing); var backgroundGeometry = new StreamGeometry(); using (var ctx = backgroundGeometry.Open()) { GeometryBuilder.DrawRoundedCornersRectangle(ctx, ref backgroundOuterKeypoints); } _backgroundGeometryCache = backgroundGeometry; } else { _backgroundGeometryCache = null; } if (boundRect.Width != 0 && boundRect.Height != 0) { var borderInnerKeypoints = GeometryBuilder.CalculateRoundedCornersRectangleWinUI( boundRect, borderThickness, cornerRadius, BackgroundSizing.InnerBorderEdge); var borderOuterKeypoints = GeometryBuilder.CalculateRoundedCornersRectangleWinUI( boundRect, borderThickness, cornerRadius, BackgroundSizing.OuterBorderEdge); var borderInnerGeometry = new StreamGeometry(); using (var ctx = borderInnerGeometry.Open()) { GeometryBuilder.DrawRoundedCornersRectangle(ctx, ref borderInnerKeypoints); } var borderOuterGeometry = new StreamGeometry(); using (var ctx = borderOuterGeometry.Open()) { GeometryBuilder.DrawRoundedCornersRectangle(ctx, ref borderOuterKeypoints); } _borderGeometryCache = new CombinedGeometry(GeometryCombineMode.Exclude, borderOuterGeometry, borderInnerGeometry); } else { _borderGeometryCache = null; } } } public void Render( DrawingContext context, Size finalSize, Thickness borderThickness, CornerRadius cornerRadius, BackgroundSizing backgroundSizing, IBrush? background, IBrush? borderBrush, BoxShadows boxShadows) { if (_size != finalSize || _borderThickness != borderThickness || _cornerRadius != cornerRadius || _backgroundSizing != backgroundSizing || !_initialized) { Update(finalSize, borderThickness, cornerRadius, backgroundSizing); } if (_useComplexRendering) { if (_backgroundGeometryCache != null) { context.DrawGeometry(background, null, _backgroundGeometryCache); } if (_borderGeometryCache != null) { context.DrawGeometry(borderBrush, null, _borderGeometryCache); } } else { var thickness = _borderThickness.Top; Pen.TryModifyOrCreate(ref _cachedPen, borderBrush, thickness); var rect = new Rect(_size); if (!MathUtilities.IsZero(thickness)) rect = rect.Deflate(thickness * 0.5); var rrect = new RoundedRect(rect, _cornerRadius.TopLeft, _cornerRadius.TopRight, _cornerRadius.BottomRight, _cornerRadius.BottomLeft); context.DrawRectangle(background, _cachedPen, rrect, boxShadows); } } } }
BorderRenderHelper
csharp
grandnode__grandnode2
src/Web/Grand.Web/Features/Models/Vendors/GetVendorReviews.cs
{ "start": 95, "end": 213 }
public class ____ : IRequest<VendorReviewsModel> { public Domain.Vendors.Vendor Vendor { get; set; } }
GetVendorReviews
csharp
protobuf-net__protobuf-net
src/protobuf-net/Internal/Serializers/TagDecorator.cs
{ "start": 137, "end": 4976 }
internal sealed class ____ : ProtoDecoratorBase, IProtoTypeSerializer { SerializerFeatures IProtoTypeSerializer.Features => wireType.AsFeatures(); bool IProtoTypeSerializer.IsSubType => Tail is IProtoTypeSerializer pts && pts.IsSubType; public bool HasCallbacks(TypeModel.CallbackType callbackType) => Tail is IProtoTypeSerializer pts && pts.HasCallbacks(callbackType); public bool CanCreateInstance() => Tail is IProtoTypeSerializer pts && pts.CanCreateInstance(); public object CreateInstance(ISerializationContext source) => ((IProtoTypeSerializer)Tail).CreateInstance(source); public void Callback(object value, TypeModel.CallbackType callbackType, ISerializationContext context) => (Tail as IProtoTypeSerializer)?.Callback(value, callbackType, context); public void EmitCallback(Compiler.CompilerContext ctx, Compiler.Local valueFrom, TypeModel.CallbackType callbackType) { // we only expect this to be invoked if HasCallbacks returned true, so implicitly Tail // **must** be of the correct type ((IProtoTypeSerializer)Tail).EmitCallback(ctx, valueFrom, callbackType); } public void EmitCreateInstance(Compiler.CompilerContext ctx, bool callNoteObject) { ((IProtoTypeSerializer)Tail).EmitCreateInstance(ctx, callNoteObject); } bool IProtoTypeSerializer.ShouldEmitCreateInstance => Tail is IProtoTypeSerializer pts && pts.ShouldEmitCreateInstance; public override Type ExpectedType => Tail.ExpectedType; Type IProtoTypeSerializer.BaseType => ExpectedType; public TagDecorator(int fieldNumber, WireType wireType, bool strict, IRuntimeProtoSerializerNode tail) : base(tail) { this.fieldNumber = fieldNumber; this.wireType = wireType; this.strict = strict; } public override bool RequiresOldValue => Tail.RequiresOldValue; public override bool ReturnsValue => Tail.ReturnsValue; private readonly bool strict; private readonly int fieldNumber; private readonly WireType wireType; private bool NeedsHint => ((int)wireType & ~7) != 0; public override object Read(ref ProtoReader.State state, object value) { Debug.Assert(fieldNumber == state.FieldNumber); if (strict) { state.Assert(wireType); } else if (NeedsHint) { state.Hint(wireType); } return Tail.Read(ref state, value); } public override void Write(ref ProtoWriter.State state, object value) { if (Tail is IDirectRuntimeWriteNode dw && dw.CanDirectWrite(wireType)) { dw.DirectWrite(fieldNumber, wireType, ref state, value); } else { state.WriteFieldHeader(fieldNumber, wireType); Tail.Write(ref state, value); } } bool IProtoTypeSerializer.HasInheritance => false; void IProtoTypeSerializer.EmitReadRoot(Compiler.CompilerContext ctx, Compiler.Local valueFrom) => EmitRead(ctx, valueFrom); void IProtoTypeSerializer.EmitWriteRoot(Compiler.CompilerContext ctx, Compiler.Local valueFrom) => EmitWrite(ctx, valueFrom); protected override void EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom) { if (Tail is IDirectWriteNode dw && dw.CanEmitDirectWrite(wireType)) { dw.EmitDirectWrite(fieldNumber, wireType, ctx, valueFrom); } else { ctx.LoadState(); ctx.LoadValue((int)fieldNumber); ctx.LoadValue((int)wireType); ctx.EmitCall(typeof(ProtoWriter.State).GetMethod(nameof(ProtoWriter.State.WriteFieldHeader))); Tail.EmitWrite(ctx, valueFrom); } } public bool CanEmitDirectWrite() => Tail is IDirectWriteNode dw && dw.CanEmitDirectWrite(wireType); public void EmitDirectWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom) => ((IDirectWriteNode)Tail).EmitDirectWrite(fieldNumber, wireType, ctx, valueFrom); protected override void EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom) { if (strict || NeedsHint) { ctx.LoadState(); ctx.LoadValue((int)wireType); string name = strict ? nameof(ProtoReader.State.Assert) : nameof(ProtoReader.State.Hint); ctx.EmitCall(typeof(ProtoReader.State).GetMethod(name, new[] { typeof(WireType) })); } Tail.EmitRead(ctx, valueFrom); } } }
TagDecorator
csharp
dotnet__orleans
src/Orleans.Streaming/MemoryStreams/MemoryStreamProviderBuilder.cs
{ "start": 332, "end": 770 }
internal sealed class ____ : IProviderBuilder<ISiloBuilder>, IProviderBuilder<IClientBuilder> { public void Configure(ISiloBuilder builder, string name, IConfigurationSection configurationSection) { builder.AddMemoryStreams(name); } public void Configure(IClientBuilder builder, string name, IConfigurationSection configurationSection) { builder.AddMemoryStreams(name); } }
MemoryStreamProviderBuilder
csharp
microsoft__semantic-kernel
dotnet/test/VectorData/CosmosMongoDB.UnitTests/CosmosMongoCollectionTests.cs
{ "start": 22970, "end": 23196 }
private sealed class ____ { [VectorStoreKey] public string? Id { get; set; } [VectorStoreData(StorageName = "hotel_name")] public string? HotelName { get; set; } }
VectorStoreTestModel
csharp
Cysharp__UniTask
src/UniTask/Assets/Plugins/UniTask/Runtime/Triggers/MonoBehaviourMessagesTriggers.cs
{ "start": 139024, "end": 140225 }
public sealed class ____ : AsyncTriggerBase<PointerEventData>, IPointerExitHandler { void IPointerExitHandler.OnPointerExit(PointerEventData eventData) { RaiseEvent((eventData)); } public IAsyncOnPointerExitHandler GetOnPointerExitAsyncHandler() { return new AsyncTriggerHandler<PointerEventData>(this, false); } public IAsyncOnPointerExitHandler GetOnPointerExitAsyncHandler(CancellationToken cancellationToken) { return new AsyncTriggerHandler<PointerEventData>(this, cancellationToken, false); } public UniTask<PointerEventData> OnPointerExitAsync() { return ((IAsyncOnPointerExitHandler)new AsyncTriggerHandler<PointerEventData>(this, true)).OnPointerExitAsync(); } public UniTask<PointerEventData> OnPointerExitAsync(CancellationToken cancellationToken) { return ((IAsyncOnPointerExitHandler)new AsyncTriggerHandler<PointerEventData>(this, cancellationToken, true)).OnPointerExitAsync(); } } #endif #endregion #region PointerUp #if !UNITY_2019_1_OR_NEWER || UNITASK_UGUI_SUPPORT
AsyncPointerExitTrigger
csharp
ServiceStack__ServiceStack
ServiceStack/src/ServiceStack/Validators.cs
{ "start": 580, "end": 1490 }
public class ____(SharpPage code) : PropertyValidator(new LanguageStringSource(nameof(PredicateValidator))), IPredicateValidator { public SharpPage Code { get; } = code; public override bool ShouldValidateAsynchronously(IValidationContext context) => true; //public override bool ShouldValidateAsync(ValidationContext context) => true; protected override async Task<bool> IsValidAsync(PropertyValidatorContext context, CancellationToken cancellation) { var ret = await HostContext.AppHost.EvalScriptAsync(context.ToPageResult(Code), context.ParentContext.Request); return DefaultScripts.isTruthy(ret); } protected override bool IsValid(PropertyValidatorContext context) { var ret = HostContext.AppHost.EvalScript(context.ToPageResult(Code), context.ParentContext.Request); return DefaultScripts.isTruthy(ret); } }
ScriptConditionValidator
csharp
nuke-build__nuke
source/Nuke.Utilities.Tests/Collections/EnumerableExtensionsTest.cs
{ "start": 279, "end": 922 }
public class ____ { [Fact] public void SingleOrDefaultOrError_ThrowsExceptionWithMessage() { var x = new[] { "a", "a" }; Action a = () => x.SingleOrDefaultOrError("error"); a.Should().Throw<InvalidOperationException>().WithMessage("error"); } [Theory] [InlineData(new[] { "a", "b", "c" }, "a", "a")] [InlineData(new[] { "a", "b", "c" }, "d", null)] public void SingleOrDefaultOrError(string[] enumerable, string equalsWith, string expectedValue) { enumerable.SingleOrDefaultOrError(x => x.Equals(equalsWith), "error").Should().Be(expectedValue); } }
EnumerableExtensionsTest
csharp
mongodb__mongo-csharp-driver
src/MongoDB.Driver/Linq/Linq3Implementation/Translators/ExpressionToPipelineTranslators/SelectMethodToPipelineTranslator.cs
{ "start": 1089, "end": 3270 }
internal static class ____ { // public static methods public static TranslatedPipeline Translate(TranslationContext context, MethodCallExpression expression) { var method = expression.Method; var arguments = expression.Arguments; if (method.Is(QueryableMethod.Select)) { var sourceExpression = arguments[0]; var pipeline = ExpressionToPipelineTranslator.Translate(context, sourceExpression); var selectorLambda = ExpressionHelper.UnquoteLambda(arguments[1]); if (selectorLambda.Body == selectorLambda.Parameters[0]) { return pipeline; // ignore identity projection: Select(x => x) } // check for client side projection after handling identity projection ClientSideProjectionHelper.ThrowIfClientSideProjection(expression, pipeline, method); var sourceSerializer = pipeline.OutputSerializer; AstProjectStage projectStage; IBsonSerializer projectionSerializer; try { var selectorTranslation = ExpressionToAggregationExpressionTranslator.TranslateLambdaBody(context, selectorLambda, sourceSerializer, asRoot: true); (projectStage, projectionSerializer) = ProjectionHelper.CreateProjectStage(selectorTranslation); } catch (ExpressionNotSupportedException) when (context.TranslationOptions?.EnableClientSideProjections ?? false) { (projectStage, projectionSerializer) = ClientSideProjectionTranslator.CreateProjectSnippetsStage(context, selectorLambda, sourceSerializer); } return projectStage == null ? pipeline.WithNewOutputSerializer(projectionSerializer) : // project directly off $$ROOT with no $project stage pipeline.AddStage(projectStage, projectionSerializer); } throw new ExpressionNotSupportedException(expression); } } }
SelectMethodToPipelineTranslator
csharp
smartstore__Smartstore
src/Smartstore.Web/Models/Common/GdprConsentModel.cs
{ "start": 46, "end": 203 }
public partial class ____ : ModelBase { public bool GdprConsent { get; set; } public bool SmallDisplay { get; set; } } }
GdprConsentModel
csharp
ServiceStack__ServiceStack
ServiceStack/tests/ServiceStack.WebHost.Endpoints.Tests/CustomHttpMethodTests.cs
{ "start": 1182, "end": 2937 }
class ____ : AppSelfHostBase { public AppHost() : base(nameof(CustomHttpMethodTests), typeof(CustomMethodService).Assembly) { } public override void Configure(Container container) { } } private ServiceStackHost appHost; public CustomHttpMethodTests() { appHost = new AppHost() .Init() .Start(Config.ListeningOn); } [OneTimeTearDown] public void OneTimeTearDown() => appHost.Dispose(); [Test] public void Does_execute_HEAD_Request_returning_custom_HttpResult() { var response = Config.ListeningOn.AppendPath("custom-method","result").AddQueryParam("id", 1) .SendStringToUrl(method: "HEAD", responseFilter: res => { Assert.That(res.GetHeader("X-Method"), Is.EqualTo("HEAD")); Assert.That(res.GetHeader("X-Id"), Is.EqualTo("1")); Assert.That(res.MatchesContentType("video/mp4")); Assert.That(res.GetContentLength(), Is.EqualTo(100)); }); Assert.That(response, Is.Empty); } [Test] public void Does_execute_HEAD_Request_writing_custom_headers() { var response = Config.ListeningOn.AppendPath("custom-method","headers").AddQueryParam("id", 1) .SendStringToUrl(method: "HEAD", responseFilter: res => { Assert.That(res.GetHeader("X-Method"), Is.EqualTo("HEAD")); Assert.That(res.GetHeader("X-Id"), Is.EqualTo("1")); Assert.That(res.MatchesContentType("video/mp4")); Assert.That(res.GetContentLength(), Is.EqualTo(100)); }); Assert.That(response, Is.Empty); } }
AppHost
csharp
AutoMapper__AutoMapper
src/UnitTests/AutoMapperSpecBase.cs
{ "start": 4587, "end": 5208 }
class ____ : ExpressionVisitor { public int Count; protected override Expression VisitMethodCall(MethodCallExpression node) { if (node.Method.Name == "FirstOrDefault") { Count++; } return base.VisitMethodCall(node); } public static void Assert(IQueryable queryable, int count) => Assert(queryable.Expression, count); public static void Assert(Expression expression, int count) { var firstOrDefault = new FirstOrDefaultCounter(); firstOrDefault.Visit(expression); firstOrDefault.Count.ShouldBe(count); } }
FirstOrDefaultCounter
csharp
dotnet__efcore
test/EFCore.Design.Tests/Migrations/Design/CSharpMigrationsGeneratorTest.cs
{ "start": 30558, "end": 32646 }
partial class ____ { /// <inheritdoc /> protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder.HasAnnotation("Some:EnumValue", RegexOptions.Multiline); modelBuilder.Entity("T1", b => { b.Property<int>("Id") .HasColumnType("int"); b.Property<string>("C2") .IsRequired() .HasColumnType("nvarchar(max)"); b.Property<int>("C3") .HasColumnType("int"); b.HasKey("Id"); b.ToTable("T1"); }); #pragma warning restore 612, 618 } } } """, migrationMetadataCode, ignoreLineEndingDifferences: true); var build = new BuildSource { References = { BuildReference.ByName("Microsoft.EntityFrameworkCore.Design.Tests"), BuildReference.ByName("Microsoft.EntityFrameworkCore"), BuildReference.ByName("Microsoft.EntityFrameworkCore.Relational") }, Sources = { { "Migration.cs", migrationCode }, { "MigrationSnapshot.cs", migrationMetadataCode } }, EmitDocumentationDiagnostics = true }; var assembly = build.BuildInMemory(); var migrationType = assembly.GetType("MyNamespace.MyMigration", throwOnError: true, ignoreCase: false); var contextTypeAttribute = migrationType.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(4, migration.UpOperations.Count); Assert.Empty(migration.DownOperations); Assert.Single(migration.TargetModel.GetEntityTypes()); }
MyMigration
csharp
npgsql__npgsql
src/Npgsql/NpgsqlDataSourceBuilder.cs
{ "start": 21356, "end": 21610 }
enum ____. /// The translation strategy can be controlled by the <paramref name="nameTranslator"/> parameter, /// which defaults to <see cref="NpgsqlSnakeCaseNameTranslator"/>. /// You can also use the <see cref="PgNameAttribute"/> on your
labels
csharp
dotnet__orleans
src/Orleans.Streaming/Providers/IStreamProviderRuntime.cs
{ "start": 210, "end": 279 }
interface ____ manager of streaming providers /// </summary>
for
csharp
ServiceStack__ServiceStack
ServiceStack/tests/NorthwindAuto/ServiceInterface/BackgroundJobServices.cs
{ "start": 107, "end": 540 }
public class ____(IBackgroundJobs jobs) : Service { public object Any(QueueCheckUrl request) { var options = new BackgroundJobOptions().PopulateWith(request); var jobRef = jobs.EnqueueCommand<CheckUrlsCommand>(new CheckUrls { Urls = [request.Url] }, options); return new QueueCheckUrlResponse { Id = jobRef.Id, RefId = jobRef.RefId, }; } }
BackgroundJobServices
csharp
xunit__xunit
src/xunit.v2.tests/Acceptance/Xunit2TheoryAcceptanceTests.cs
{ "start": 44470, "end": 44907 }
class ____ { public static IEnumerable<object[]> Data { get { yield return new object[] { 42, 'a', new ClassUnderTest() }; yield return new object[] { 0, null, null }; } } [Theory] [MemberData("Data")] public void TestViaInlineData(int x, char? y, object z) { Assert.Equal(0, x); // Fails the first data item Assert.NotNull(z); // Fails the second data item } } }
ClassUnderTest
csharp
nopSolutions__nopCommerce
src/Libraries/Nop.Services/Catalog/PriceCalculationService.cs
{ "start": 368, "end": 23811 }
public partial class ____ : IPriceCalculationService { #region Fields protected readonly CatalogSettings _catalogSettings; protected readonly CurrencySettings _currencySettings; protected readonly ICategoryService _categoryService; protected readonly ICurrencyService _currencyService; protected readonly ICustomerService _customerService; protected readonly IDiscountService _discountService; protected readonly IManufacturerService _manufacturerService; protected readonly IProductAttributeParser _productAttributeParser; protected readonly IProductService _productService; protected readonly IStaticCacheManager _staticCacheManager; #endregion #region Ctor public PriceCalculationService(CatalogSettings catalogSettings, CurrencySettings currencySettings, ICategoryService categoryService, ICurrencyService currencyService, ICustomerService customerService, IDiscountService discountService, IManufacturerService manufacturerService, IProductAttributeParser productAttributeParser, IProductService productService, IStaticCacheManager staticCacheManager) { _catalogSettings = catalogSettings; _currencySettings = currencySettings; _categoryService = categoryService; _currencyService = currencyService; _customerService = customerService; _discountService = discountService; _manufacturerService = manufacturerService; _productAttributeParser = productAttributeParser; _productService = productService; _staticCacheManager = staticCacheManager; } #endregion #region Utilities /// <summary> /// Gets allowed discounts applied to product /// </summary> /// <param name="product">Product</param> /// <param name="customer">Customer</param> /// <returns> /// A task that represents the asynchronous operation /// The task result contains the discounts /// </returns> protected virtual async Task<IList<Discount>> GetAllowedDiscountsAppliedToProductAsync(Product product, Customer customer) { var allowedDiscounts = new List<Discount>(); if (_catalogSettings.IgnoreDiscounts) return allowedDiscounts; var couponCodesToValidate = await _customerService.ParseAppliedDiscountCouponCodesAsync(customer); foreach (var discount in await _discountService.GetAppliedDiscountsAsync(product)) if (discount.DiscountType == DiscountType.AssignedToSkus && (await _discountService.ValidateDiscountAsync(discount, customer, couponCodesToValidate)).IsValid) allowedDiscounts.Add(discount); return allowedDiscounts; } /// <summary> /// Gets allowed discounts applied to categories /// </summary> /// <param name="product">Product</param> /// <param name="customer">Customer</param> /// <returns> /// A task that represents the asynchronous operation /// The task result contains the discounts /// </returns> protected virtual async Task<IList<Discount>> GetAllowedDiscountsAppliedToCategoriesAsync(Product product, Customer customer) { var allowedDiscounts = new List<Discount>(); if (_catalogSettings.IgnoreDiscounts) return allowedDiscounts; //load cached discount models (performance optimization) foreach (var discount in await _discountService.GetAllDiscountsAsync(DiscountType.AssignedToCategories)) { //load identifier of categories with this discount applied to var discountCategoryIds = await _categoryService.GetAppliedCategoryIdsAsync(discount, customer); //compare with categories of this product var productCategoryIds = new List<int>(); if (discountCategoryIds.Any()) { productCategoryIds = (await _categoryService .GetProductCategoriesByProductIdAsync(product.Id)) .Select(x => x.CategoryId) .ToList(); } var couponCodesToValidate = await _customerService.ParseAppliedDiscountCouponCodesAsync(customer); foreach (var categoryId in productCategoryIds) { if (!discountCategoryIds.Contains(categoryId)) continue; if (!_discountService.ContainsDiscount(allowedDiscounts, discount) && (await _discountService.ValidateDiscountAsync(discount, customer, couponCodesToValidate)).IsValid) allowedDiscounts.Add(discount); } } return allowedDiscounts; } /// <summary> /// Gets allowed discounts applied to manufacturers /// </summary> /// <param name="product">Product</param> /// <param name="customer">Customer</param> /// <returns> /// A task that represents the asynchronous operation /// The task result contains the discounts /// </returns> protected virtual async Task<IList<Discount>> GetAllowedDiscountsAppliedToManufacturersAsync(Product product, Customer customer) { var allowedDiscounts = new List<Discount>(); if (_catalogSettings.IgnoreDiscounts) return allowedDiscounts; foreach (var discount in await _discountService.GetAllDiscountsAsync(DiscountType.AssignedToManufacturers)) { //load identifier of manufacturers with this discount applied to var discountManufacturerIds = await _manufacturerService.GetAppliedManufacturerIdsAsync(discount, customer); //compare with manufacturers of this product var productManufacturerIds = new List<int>(); if (discountManufacturerIds.Any()) { productManufacturerIds = (await _manufacturerService .GetProductManufacturersByProductIdAsync(product.Id)) .Select(x => x.ManufacturerId) .ToList(); } var couponCodesToValidate = await _customerService.ParseAppliedDiscountCouponCodesAsync(customer); foreach (var manufacturerId in productManufacturerIds) { if (!discountManufacturerIds.Contains(manufacturerId)) continue; if (!_discountService.ContainsDiscount(allowedDiscounts, discount) && (await _discountService.ValidateDiscountAsync(discount, customer, couponCodesToValidate)).IsValid) allowedDiscounts.Add(discount); } } return allowedDiscounts; } /// <summary> /// Gets allowed discounts /// </summary> /// <param name="product">Product</param> /// <param name="customer">Customer</param> /// <returns> /// A task that represents the asynchronous operation /// The task result contains the discounts /// </returns> protected virtual async Task<IList<Discount>> GetAllowedDiscountsAsync(Product product, Customer customer) { var allowedDiscounts = new List<Discount>(); if (_catalogSettings.IgnoreDiscounts) return allowedDiscounts; //discounts applied to products foreach (var discount in await GetAllowedDiscountsAppliedToProductAsync(product, customer)) if (!_discountService.ContainsDiscount(allowedDiscounts, discount)) allowedDiscounts.Add(discount); //discounts applied to categories foreach (var discount in await GetAllowedDiscountsAppliedToCategoriesAsync(product, customer)) if (!_discountService.ContainsDiscount(allowedDiscounts, discount)) allowedDiscounts.Add(discount); //discounts applied to manufacturers foreach (var discount in await GetAllowedDiscountsAppliedToManufacturersAsync(product, customer)) if (!_discountService.ContainsDiscount(allowedDiscounts, discount)) allowedDiscounts.Add(discount); return allowedDiscounts; } /// <summary> /// Gets discount amount /// </summary> /// <param name="product">Product</param> /// <param name="customer">The customer</param> /// <param name="productPriceWithoutDiscount">Already calculated product price without discount</param> /// <returns> /// A task that represents the asynchronous operation /// The task result contains the discount amount, Applied discounts /// </returns> protected virtual async Task<(decimal, List<Discount>)> GetDiscountAmountAsync(Product product, Customer customer, decimal productPriceWithoutDiscount) { ArgumentNullException.ThrowIfNull(product); var appliedDiscounts = new List<Discount>(); var appliedDiscountAmount = decimal.Zero; //we don't apply discounts to products with price entered by a customer if (product.CustomerEntersPrice) return (appliedDiscountAmount, appliedDiscounts); //discounts are disabled if (_catalogSettings.IgnoreDiscounts) return (appliedDiscountAmount, appliedDiscounts); var allowedDiscounts = await GetAllowedDiscountsAsync(product, customer); //no discounts if (!allowedDiscounts.Any()) return (appliedDiscountAmount, appliedDiscounts); appliedDiscounts = _discountService.GetPreferredDiscount(allowedDiscounts, productPriceWithoutDiscount, out appliedDiscountAmount); return (appliedDiscountAmount, appliedDiscounts); } #endregion #region Methods /// <summary> /// Gets the final price /// </summary> /// <param name="product">Product</param> /// <param name="customer">The customer</param> /// <param name="store">Store</param> /// <param name="additionalCharge">Additional charge</param> /// <param name="includeDiscounts">A value indicating whether include discounts or not for final price computation</param> /// <param name="quantity">Shopping cart item quantity</param> /// <returns> /// A task that represents the asynchronous operation /// The task result contains the final price without discounts, Final price, Applied discount amount, Applied discounts /// </returns> public virtual async Task<(decimal priceWithoutDiscounts, decimal finalPrice, decimal appliedDiscountAmount, List<Discount> appliedDiscounts)> GetFinalPriceAsync(Product product, Customer customer, Store store, decimal additionalCharge = 0, bool includeDiscounts = true, int quantity = 1) { return await GetFinalPriceAsync(product, customer, store, additionalCharge, includeDiscounts, quantity, null, null); } /// <summary> /// Gets the final price /// </summary> /// <param name="product">Product</param> /// <param name="customer">The customer</param> /// <param name="store">Store</param> /// <param name="additionalCharge">Additional charge</param> /// <param name="includeDiscounts">A value indicating whether include discounts or not for final price computation</param> /// <param name="quantity">Shopping cart item quantity</param> /// <param name="rentalStartDate">Rental period start date (for rental products)</param> /// <param name="rentalEndDate">Rental period end date (for rental products)</param> /// <returns> /// A task that represents the asynchronous operation /// The task result contains the final price without discounts, Final price, Applied discount amount, Applied discounts /// </returns> public virtual async Task<(decimal priceWithoutDiscounts, decimal finalPrice, decimal appliedDiscountAmount, List<Discount> appliedDiscounts)> GetFinalPriceAsync(Product product, Customer customer, Store store, decimal additionalCharge, bool includeDiscounts, int quantity, DateTime? rentalStartDate, DateTime? rentalEndDate) { return await GetFinalPriceAsync(product, customer, store, null, additionalCharge, includeDiscounts, quantity, rentalStartDate, rentalEndDate); } /// <summary> /// Gets the final price /// </summary> /// <param name="product">Product</param> /// <param name="customer">The customer</param> /// <param name="store">Store</param> /// <param name="overriddenProductPrice">Overridden product price. If specified, then it'll be used instead of a product price. For example, used with product attribute combinations</param> /// <param name="additionalCharge">Additional charge</param> /// <param name="includeDiscounts">A value indicating whether include discounts or not for final price computation</param> /// <param name="quantity">Shopping cart item quantity</param> /// <param name="rentalStartDate">Rental period start date (for rental products)</param> /// <param name="rentalEndDate">Rental period end date (for rental products)</param> /// <returns> /// A task that represents the asynchronous operation /// The task result contains the final price without discounts, Final price, Applied discount amount, Applied discounts /// </returns> public virtual async Task<(decimal priceWithoutDiscounts, decimal finalPrice, decimal appliedDiscountAmount, List<Discount> appliedDiscounts)> GetFinalPriceAsync(Product product, Customer customer, Store store, decimal? overriddenProductPrice, decimal additionalCharge, bool includeDiscounts, int quantity, DateTime? rentalStartDate, DateTime? rentalEndDate) { ArgumentNullException.ThrowIfNull(product); var cacheKey = _staticCacheManager.PrepareKeyForDefaultCache(NopCatalogDefaults.ProductPriceCacheKey, product, overriddenProductPrice, additionalCharge, includeDiscounts, quantity, await _customerService.GetCustomerRoleIdsAsync(customer), store); //we do not cache price if this not allowed by settings or if the product is rental product //otherwise, it can cause memory leaks (to store all possible date period combinations) if (!_catalogSettings.CacheProductPrices || product.IsRental) cacheKey.CacheTime = 0; decimal rezPrice; decimal rezPriceWithoutDiscount; decimal discountAmount; List<Discount> appliedDiscounts; (rezPriceWithoutDiscount, rezPrice, discountAmount, appliedDiscounts) = await _staticCacheManager.GetAsync(cacheKey, async () => { var discounts = new List<Discount>(); var appliedDiscountAmount = decimal.Zero; //initial price var price = overriddenProductPrice ?? product.Price; //tier prices var tierPrice = await _productService.GetPreferredTierPriceAsync(product, customer, store, quantity); if (tierPrice != null) price = tierPrice.Price; //additional charge price += additionalCharge; //rental products if (product.IsRental) if (rentalStartDate.HasValue && rentalEndDate.HasValue) price *= _productService.GetRentalPeriods(product, rentalStartDate.Value, rentalEndDate.Value); var priceWithoutDiscount = price; if (includeDiscounts) { //discount var (tmpDiscountAmount, tmpAppliedDiscounts) = await GetDiscountAmountAsync(product, customer, price); price -= tmpDiscountAmount; if (tmpAppliedDiscounts?.Any() ?? false) { discounts.AddRange(tmpAppliedDiscounts); appliedDiscountAmount = tmpDiscountAmount; } } if (price < decimal.Zero) price = decimal.Zero; if (priceWithoutDiscount < decimal.Zero) priceWithoutDiscount = decimal.Zero; return (priceWithoutDiscount, price, appliedDiscountAmount, discounts); }); return (rezPriceWithoutDiscount, rezPrice, discountAmount, appliedDiscounts); } /// <summary> /// Gets the product cost (one item) /// </summary> /// <param name="product">Product</param> /// <param name="attributesXml">Shopping cart item attributes in XML</param> /// <returns> /// A task that represents the asynchronous operation /// The task result contains the product cost (one item) /// </returns> public virtual async Task<decimal> GetProductCostAsync(Product product, string attributesXml) { ArgumentNullException.ThrowIfNull(product); var cost = product.ProductCost; var attributeValues = await _productAttributeParser.ParseProductAttributeValuesAsync(attributesXml); foreach (var attributeValue in attributeValues) { switch (attributeValue.AttributeValueType) { case AttributeValueType.Simple: //simple attribute cost += attributeValue.Cost; break; case AttributeValueType.AssociatedToProduct: //bundled product var associatedProduct = await _productService.GetProductByIdAsync(attributeValue.AssociatedProductId); if (associatedProduct != null) cost += associatedProduct.ProductCost * attributeValue.Quantity; break; default: break; } } return cost; } /// <summary> /// Get a price adjustment of a product attribute value /// </summary> /// <param name="product">Product</param> /// <param name="value">Product attribute value</param> /// <param name="customer">Customer</param> /// <param name="store">Store</param> /// <param name="productPrice">Product price (null for using the base product price)</param> /// <param name="quantity">Shopping cart item quantity</param> /// <returns> /// A task that represents the asynchronous operation /// The task result contains the price adjustment /// </returns> public virtual async Task<decimal> GetProductAttributeValuePriceAdjustmentAsync(Product product, ProductAttributeValue value, Customer customer, Store store, decimal? productPrice = null, int quantity = 1) { ArgumentNullException.ThrowIfNull(value); var adjustment = decimal.Zero; switch (value.AttributeValueType) { case AttributeValueType.Simple: //simple attribute if (value.PriceAdjustmentUsePercentage) { if (!productPrice.HasValue) productPrice = (await GetFinalPriceAsync(product, customer, store, quantity: quantity)).finalPrice; adjustment = (decimal)((float)productPrice * (float)value.PriceAdjustment / 100f); } else { adjustment = value.PriceAdjustment; } break; case AttributeValueType.AssociatedToProduct: //bundled product var associatedProduct = await _productService.GetProductByIdAsync(value.AssociatedProductId); if (associatedProduct != null) adjustment = (await GetFinalPriceAsync(associatedProduct, customer, store)).finalPrice * value.Quantity; break; default: break; } return adjustment; } /// <summary> /// Round a product or order total for the currency /// </summary> /// <param name="value">Value to round</param> /// <param name="currency">Currency; pass null to use the primary store currency</param> /// <returns> /// A task that represents the asynchronous operation /// The task result contains the rounded value /// </returns> public virtual async Task<decimal> RoundPriceAsync(decimal value, Currency currency = null) { //we use this method because some currencies (e.g. Hungarian Forint or Swiss Franc) use non-standard rules for rounding //you can implement any rounding logic here currency ??= await _currencyService.GetCurrencyByIdAsync(_currencySettings.PrimaryStoreCurrencyId); return Round(value, currency.RoundingType); } /// <summary> /// Round /// </summary> /// <param name="value">Value to round</param> /// <param name="roundingType">The rounding type</param> /// <returns>Rounded value</returns> public virtual decimal Round(decimal value, RoundingType roundingType) { //default round (Rounding001) var rez = Math.Round(value, 2); var fractionPart = (rez - Math.Truncate(rez)) * 10; //cash rounding not needed if (fractionPart == 0) return rez; //Cash rounding (details: https://en.wikipedia.org/wiki/Cash_rounding) switch (roundingType) { //rounding with 0.05 or 5 intervals case RoundingType.Rounding005Up: case RoundingType.Rounding005Down: fractionPart = (fractionPart - Math.Truncate(fractionPart)) * 10; fractionPart %= 5; if (fractionPart == 0) break; if (roundingType == RoundingType.Rounding005Up) fractionPart = 5 - fractionPart; else fractionPart *= -1; rez += fractionPart / 100; break; //rounding with 0.10 intervals case RoundingType.Rounding01Up: case RoundingType.Rounding01Down: fractionPart = (fractionPart - Math.Truncate(fractionPart)) * 10; if (roundingType == RoundingType.Rounding01Down && fractionPart == 5) fractionPart = -5; else fractionPart = fractionPart < 5 ? fractionPart * -1 : 10 - fractionPart; rez += fractionPart / 100; break; //rounding with 0.50 intervals case RoundingType.Rounding05: fractionPart *= 10; fractionPart = fractionPart < 25 ? fractionPart * -1 : fractionPart < 50 || fractionPart < 75 ? 50 - fractionPart : 100 - fractionPart; rez += fractionPart / 100; break; //rounding with 1.00 intervals case RoundingType.Rounding1: case RoundingType.Rounding1Up: fractionPart *= 10; if (roundingType == RoundingType.Rounding1Up && fractionPart > 0) rez = Math.Truncate(rez) + 1; else rez = fractionPart < 50 ? Math.Truncate(rez) : Math.Truncate(rez) + 1; break; case RoundingType.Rounding001: default: break; } return rez; } #endregion }
PriceCalculationService
csharp
unoplatform__uno
src/Uno.Sdk/Tasks/ImplicitPackagesResolver.cs
{ "start": 355, "end": 14883 }
public sealed class ____ : Task { private readonly List<string> _existingReferences = []; private PackageManifest? _manifest; private NuGetVersion? _unoVersion; public bool SdkDebugging { get; set; } public bool SingleProject { get; set; } [Required] public string OutputType { get; set; } = null!; public bool Optimize { get; set; } [Required] public string IntermediateOutput { get; set; } = null!; public string? UnoFeatures { get; set; } [Required] public string TargetFramework { get; set; } = null!; private string TargetFrameworkVersion = null!; private string TargetRuntime = null!; [Required] public string ProjectName { get; set; } = null!; public string? UnoExtensionsVersion { get; set; } public string? UnoToolkitVersion { get; set; } public string? UnoThemesVersion { get; set; } public string? UnoCSharpMarkupVersion { get; set; } public string? MauiVersion { get; set; } public string? SkiaSharpVersion { get; set; } public string? SvgSkiaVersion { get; set; } public string? UnoLoggingVersion { get; set; } public string? VlcNativeWindowsAssetsVersion { get; set; } public string? MicrosoftWebView2Version { get; set; } public string? WindowsCompatibilityVersion { get; set; } public string? UnoWasmBootstrapVersion { get; set; } public string? UnoUniversalImageLoaderVersion { get; set; } public string? AndroidMaterialVersion { get; set; } public string? AndroidXLegacySupportV4Version { get; set; } public string? AndroidXSplashScreenVersion { get; set; } public string? AndroidXAppCompatVersion { get; set; } public string? AndroidXRecyclerViewVersion { get; set; } public string? AndroidXActivityVersion { get; set; } public string? AndroidXBrowserVersion { get; set; } public string? AndroidXSwipeRefreshLayoutVersion { get; set; } public string? UnoResizetizerVersion { get; set; } public string? UnoSdkExtrasVersion { get; set; } public string? UnoSettingsVersion { get; set; } public string? UnoHotDesignVersion { get; set; } public string? UnoAppMcpVersion { get; set; } public string? MicrosoftLoggingVersion { get; set; } public string? WinAppSdkVersion { get; set; } public string? WinAppSdkBuildToolsVersion { get; set; } public string? UnoCoreLoggingSingletonVersion { get; set; } public string? UnoDspTasksVersion { get; set; } public string? CommunityToolkitMvvmVersion { get; set; } public string? PrismVersion { get; set; } public string? UnoFontsVersion { get; set; } public string? AndroidXNavigationVersion { get; set; } public string? AndroidXCollectionVersion { get; set; } public string? MicrosoftIdentityClientVersion { get; set; } public ITaskItem[] ImplicitPackageReferences { get; set; } = []; public ITaskItem[] PackageReferences { get; set; } = []; public ITaskItem[] PackageVersions { get; set; } = []; private readonly List<PackageReference> _implicitPackages = []; [Output] public ITaskItem[] ImplicitPackages => [.. _implicitPackages.Distinct() .Select(x => x.ToTaskItem())]; [Output] public ITaskItem[] RemovePackageVersions => PackageVersions.Where(x => _implicitPackages.Any(ip => ip.PackageId == x.ItemSpec)).ToArray(); private UnoFeature[] _unoFeatures = []; public sealed override bool Execute() { try { if (TargetFramework.Contains('-')) { var frameworkParts = TargetFramework.Split('-'); TargetFrameworkVersion = frameworkParts[0]; var runtime = frameworkParts[1].ToLowerInvariant(); if (runtime.Contains("windows")) { TargetRuntime = runtime.StartsWith(UnoTarget.Windows, StringComparison.InvariantCultureIgnoreCase) ? UnoTarget.Windows : UnoTarget.SkiaWpf; } else { TargetRuntime = runtime; } } else { TargetFrameworkVersion = TargetFramework; TargetRuntime = UnoTarget.Reference; if (ProjectName.EndsWith("Skia.WPF", StringComparison.InvariantCultureIgnoreCase)) { TargetRuntime = UnoTarget.SkiaWpf; } else if (ProjectName.EndsWith("Skia.Linux.FrameBuffer", StringComparison.InvariantCultureIgnoreCase)) { TargetRuntime = UnoTarget.SkiaLinuxFramebuffer; } } _manifest = new PackageManifest(Log, TargetFrameworkVersion); if (NuGetVersion.TryParse(_manifest.UnoVersion, out var unoVersion)) { _unoVersion = unoVersion; } else { throw new InvalidOperationException("Unable to parse UnoVersion from the Package Manifest."); } // This needs to run before we get and Validate the Uno Features SetupRuntimePackageManifestUpdates(_manifest); _unoFeatures = GetFeatures(); if (Log.HasLoggedErrors) { return false; } foreach (var reference in ImplicitPackageReferences) { var packageId = reference.ItemSpec; var metadata = reference.CloneCustomMetadata() .Keys .Cast<string>() .ToDictionary(x => x, x => reference.GetMetadata(x)); AddPackage(packageId, metadata); } } catch (Exception ex) { Log.LogErrorFromException(ex); if (SdkDebugging) { Log.LogMessage(MessageImportance.High, ex.ToString()); } } if (_existingReferences.Count > 0) { var builder = new StringBuilder(); builder.AppendLine("Uno Platform Implicit Package references are enabled, you should remove these references from your csproj:"); _existingReferences.Select(x => $"\t<PackageReference Include=\"{x}\" />") .ToList() .ForEach(x => builder.AppendLine(x)); builder.AppendLine("See https://aka.platform.uno/UNOB0009 for more information."); Log.LogMessage(subcategory: null, code: "UNOB0009", helpKeyword: null, file: null, lineNumber: 0, columnNumber: 0, endLineNumber: 0, endColumnNumber: 0, MessageImportance.Normal, message: builder.ToString()); } #if DEBUG var missingImplicitPackages = PackageReferences.Where(x => !string.IsNullOrEmpty(x.GetMetadata("ProjectSystem")) && !_implicitPackages.Any(p => p.PackageId == x.ItemSpec)) .ToArray(); if (missingImplicitPackages.Length > 0) { System.Diagnostics.Debugger.Launch(); } #endif return !Log.HasLoggedErrors; } private void SetupRuntimePackageManifestUpdates(PackageManifest manifest) { // Checks any MSBuild parameters passed to the task to override the default versions from the bundled packages.json // This set of updates must not be conditional to features, as those may not be defined yet when the task // is invoked early. manifest.UpdateManifest(PackageManifest.Group.WasmBootstrap, UnoWasmBootstrapVersion) .UpdateManifest(PackageManifest.Group.OSLogging, UnoLoggingVersion) .UpdateManifest(PackageManifest.Group.VlcNativeWindowsAssets, VlcNativeWindowsAssetsVersion) .UpdateManifest(PackageManifest.Group.MicrosoftWebView2, MicrosoftWebView2Version) .UpdateManifest(PackageManifest.Group.CoreLogging, UnoCoreLoggingSingletonVersion) .UpdateManifest(PackageManifest.Group.UniversalImageLoading, UnoUniversalImageLoaderVersion) .UpdateManifest(PackageManifest.Group.Dsp, UnoDspTasksVersion) .UpdateManifest(PackageManifest.Group.Resizetizer, UnoResizetizerVersion) .UpdateManifest(PackageManifest.Group.SdkExtras, UnoSdkExtrasVersion) .UpdateManifest(PackageManifest.Group.Settings, UnoSettingsVersion) .UpdateManifest(PackageManifest.Group.HotDesign, UnoHotDesignVersion) .UpdateManifest(PackageManifest.Group.AppMcp, UnoAppMcpVersion) .UpdateManifest(PackageManifest.Group.SkiaSharp, SkiaSharpVersion) .UpdateManifest(PackageManifest.Group.SvgSkia, SvgSkiaVersion) .UpdateManifest(PackageManifest.Group.WinAppSdk, WinAppSdkVersion) .UpdateManifest(PackageManifest.Group.WinAppSdkBuildTools, WinAppSdkBuildToolsVersion) .UpdateManifest(PackageManifest.Group.MicrosoftLoggingConsole, MicrosoftLoggingVersion) .UpdateManifest(PackageManifest.Group.WindowsCompatibility, WindowsCompatibilityVersion) .UpdateManifest(PackageManifest.Group.MsalClient, MicrosoftIdentityClientVersion) .UpdateManifest(PackageManifest.Group.Mvvm, CommunityToolkitMvvmVersion) .UpdateManifest(PackageManifest.Group.Prism, PrismVersion) .UpdateManifest(PackageManifest.Group.UnoFonts, UnoFontsVersion) .UpdateManifest(PackageManifest.Group.AndroidMaterial, AndroidMaterialVersion) .UpdateManifest(PackageManifest.Group.AndroidXLegacySupportV4, AndroidXLegacySupportV4Version) .UpdateManifest(PackageManifest.Group.AndroidXSplashScreen, AndroidXSplashScreenVersion) .UpdateManifest(PackageManifest.Group.AndroidXAppCompat, AndroidXAppCompatVersion) .UpdateManifest(PackageManifest.Group.AndroidXRecyclerView, AndroidXRecyclerViewVersion) .UpdateManifest(PackageManifest.Group.AndroidXActivity, AndroidXActivityVersion) .UpdateManifest(PackageManifest.Group.AndroidXBrowser, AndroidXBrowserVersion) .UpdateManifest(PackageManifest.Group.AndroidXSwipeRefreshLayout, AndroidXSwipeRefreshLayoutVersion) .UpdateManifest(PackageManifest.Group.AndroidXNavigation, AndroidXNavigationVersion) .UpdateManifest(PackageManifest.Group.AndroidXCollection, AndroidXCollectionVersion) .UpdateManifest(PackageManifest.Group.CSharpMarkup, UnoCSharpMarkupVersion) .UpdateManifest(PackageManifest.Group.Extensions, UnoExtensionsVersion) .UpdateManifest(PackageManifest.Group.Toolkit, UnoToolkitVersion) .UpdateManifest(PackageManifest.Group.Themes, UnoThemesVersion) .UpdateManifest(PackageManifest.Group.Maui, MauiVersion); } private UnoFeature[] GetFeatures() { if (string.IsNullOrEmpty(UnoFeatures)) { Debug("UnoFeatures was provided as an empty or null value."); return []; } var features = Regex.Replace(UnoFeatures, @"\s", string.Empty) .Replace(',', ';'); if (string.IsNullOrEmpty(features)) { Debug("No UnoFeatures were provided."); return []; } var unoFeatures = features.Split(';') .Select(x => x.Trim()) // sanity check .Where(x => !string.IsNullOrEmpty(x)) .Distinct() .Select(ParseFeature) .Where(x => x != UnoFeature.Invalid) .ToArray(); Debug("Found {0} UnoFeatures for platform {1}.", unoFeatures.Length, TargetFramework ?? "Default"); return unoFeatures; } private UnoFeature ParseFeature(string feature) { if (Enum.TryParse<UnoFeature>(feature, true, out var unoFeature)) { Debug("Parsed UnoFeature: '{0}'.", feature); ValidateFeature(unoFeature); return unoFeature; } Log.LogWarning($"Unable to parse '{feature}' to a known Uno Feature."); return UnoFeature.Invalid; } public void ValidateFeature(UnoFeature feature) { var area = typeof(UnoFeature).GetMember(feature.ToString()) .Single(x => x.DeclaringType == typeof(UnoFeature)) .GetCustomAttribute<UnoAreaAttribute>()?.Area; if (_manifest is null) throw new ArgumentNullException(nameof(_manifest)); switch (area) { case UnoArea.Core: VerifyFeature(feature, _manifest.UnoVersion); break; case UnoArea.CSharpMarkup: VerifyFeature(feature, _manifest.GetGroupVersion(PackageManifest.Group.CSharpMarkup)); break; case UnoArea.Extensions: VerifyFeature(feature, _manifest.GetGroupVersion(PackageManifest.Group.Extensions)); break; case UnoArea.Theme: VerifyFeature(feature, _manifest.GetGroupVersion(PackageManifest.Group.Themes)); break; case UnoArea.Toolkit: VerifyFeature(feature, _manifest.GetGroupVersion(PackageManifest.Group.Toolkit)); break; } } private void VerifyFeature(UnoFeature feature, string? version, [CallerArgumentExpression(nameof(version))] string? versionName = null) { if (string.IsNullOrEmpty(version)) { Log.LogError(subcategory: "", errorCode: "UNOB0006", helpKeyword: null, helpLink: "https://aka.platform.uno/UNOB0006", file: null, lineNumber: 0, columnNumber: 0, endLineNumber: 0, endColumnNumber: 0, message: $"The UnoFeature '{feature}' was selected, but the property {versionName} was not set."); } } private void AddPackage(string packageId, IDictionary<string, string> metadata) { // 1) Check for Existing References var existingReference = PackageReferences.SingleOrDefault(x => x.ItemSpec == packageId); if (existingReference is not null) { // 1.1) Validate it has a version available if (PackageVersions.Any(x => x.ItemSpec == existingReference.ItemSpec) || !string.IsNullOrEmpty(existingReference.GetMetadata("Version")) || !string.IsNullOrEmpty(existingReference.GetMetadata("VersionOverride"))) { // 1.2) Add the PackageId to the ExistingReferences so that we can log a warning at the end. _existingReferences.Add(packageId); return; } Log.LogWarning("The Package '{0}' has an existing PackageReference with no Version attribute or associated PackageVersion. The Uno.Sdk is removing this and adding an implicit reference.", packageId); return; } // 2) Load the Version from the PackageManifest. This will get the version whether it was set through MSBuild or the bundled packages.json var version = _manifest!.GetPackageVersion(packageId); // 3) Validate the version has a value. If not attempt to get the latest version from NuGet.org if (string.IsNullOrEmpty(version)) { Log.LogWarning("The package '{0}' has no available version.", packageId); using var client = new NuGetApiClient(); var isUnoPreview = _unoVersion?.IsPreview ?? false; var preview = packageId.StartsWith("Uno.", StringComparison.InvariantCulture) && isUnoPreview; version = client.GetVersion(packageId, preview); Log.LogMessage(MessageImportance.High, "Retrieved the latest package version '{0}' for the package '{1}'.", version, packageId); } if (version is null || string.IsNullOrEmpty(version)) { Debug("Unable to locate package version for '{0}'.", packageId); return; } // 4) Ensure there is not already an existing Implicit Reference that was added (this shouldn't happen) var existing = _implicitPackages.SingleOrDefault(x => x.PackageId == packageId); if (existing is not null) { Debug("An existing Implicit Package reference has already been added for '{0}'.", packageId); return; } // 5) Add the Implicit Package Reference Debug("Adding Implicit Reference for '{0}' with version: '{1}'.", packageId, version); _implicitPackages.Add(new PackageReference(packageId, version, metadata)); } private void Debug(string message, params object[] args) { var importantance = SdkDebugging ? MessageImportance.High : MessageImportance.Low; Log.LogMessage(importantance, message, args); } }
ImplicitPackagesResolver_v0
csharp
aspnetboilerplate__aspnetboilerplate
src/Abp.Zero.Common/Authorization/Roles/AbpRoleBase.cs
{ "start": 307, "end": 371 }
class ____ role. /// </summary> [Table("AbpRoles")]
for
csharp
ServiceStack__ServiceStack
ServiceStack/tests/ServiceStack.WebHost.Endpoints.Tests/NetCoreIocTests.cs
{ "start": 1651, "end": 1777 }
public class ____ { public static int Counter; public SingletonDep() => Interlocked.Increment(ref Counter); }
SingletonDep
csharp
grandnode__grandnode2
src/Web/Grand.Web.Admin/Interfaces/IAddressAttributeViewModelService.cs
{ "start": 105, "end": 1239 }
public interface ____ { Task<(IEnumerable<AddressAttributeModel> addressAttributes, int totalCount)> PrepareAddressAttributes(); AddressAttributeModel PrepareAddressAttributeModel(); AddressAttributeModel PrepareAddressAttributeModel(AddressAttribute addressAttribute); Task<AddressAttribute> InsertAddressAttributeModel(AddressAttributeModel model); Task<AddressAttribute> UpdateAddressAttributeModel(AddressAttributeModel model, AddressAttribute addressAttribute); Task<(IEnumerable<AddressAttributeValueModel> addressAttributeValues, int totalCount)> PrepareAddressAttributeValues(string addressAttributeId); AddressAttributeValueModel PrepareAddressAttributeValueModel(string addressAttributeId); Task<AddressAttributeValue> InsertAddressAttributeValueModel(AddressAttributeValueModel model); AddressAttributeValueModel PrepareAddressAttributeValueModel(AddressAttributeValue addressAttributeValue); Task<AddressAttributeValue> UpdateAddressAttributeValueModel(AddressAttributeValueModel model, AddressAttributeValue addressAttributeValue); }
IAddressAttributeViewModelService
csharp
dotnet__efcore
src/EFCore/Metadata/Internal/InternalForeignKeyBuilder.cs
{ "start": 761, "end": 175625 }
public class ____ : AnnotatableBuilder<ForeignKey, InternalModelBuilder>, IConventionForeignKeyBuilder { /// <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> public InternalForeignKeyBuilder( ForeignKey foreignKey, InternalModelBuilder modelBuilder) : base(foreignKey, modelBuilder) { } /// <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> public virtual InternalForeignKeyBuilder? HasNavigation( string? name, bool pointsToPrincipal, ConfigurationSource configurationSource) => pointsToPrincipal ? HasNavigations( MemberIdentity.Create(name), navigationToDependent: null, configurationSource) : HasNavigations( navigationToPrincipal: null, MemberIdentity.Create(name), configurationSource); /// <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> public virtual InternalForeignKeyBuilder? HasNavigation( MemberInfo? property, bool pointsToPrincipal, ConfigurationSource configurationSource) => pointsToPrincipal ? HasNavigations( MemberIdentity.Create(property), navigationToDependent: null, configurationSource) : HasNavigations( navigationToPrincipal: null, MemberIdentity.Create(property), configurationSource); /// <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> public virtual InternalForeignKeyBuilder? HasNavigations( string? navigationToPrincipalName, string? navigationToDependentName, ConfigurationSource configurationSource) => HasNavigations( MemberIdentity.Create(navigationToPrincipalName), MemberIdentity.Create(navigationToDependentName), configurationSource); /// <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> public virtual InternalForeignKeyBuilder? HasNavigations( MemberInfo? navigationToPrincipal, MemberInfo? navigationToDependent, ConfigurationSource configurationSource) => HasNavigations( MemberIdentity.Create(navigationToPrincipal), MemberIdentity.Create(navigationToDependent), configurationSource); /// <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> public virtual InternalForeignKeyBuilder? HasNavigations( MemberIdentity? navigationToPrincipal, MemberIdentity? navigationToDependent, ConfigurationSource configurationSource) => HasNavigations( navigationToPrincipal, navigationToDependent, Metadata.PrincipalEntityType, Metadata.DeclaringEntityType, configurationSource); /// <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> public virtual InternalForeignKeyBuilder? HasNavigations( string? navigationToPrincipalName, string? navigationToDependentName, EntityType principalEntityType, EntityType dependentEntityType, ConfigurationSource configurationSource) => HasNavigations( MemberIdentity.Create(navigationToPrincipalName), MemberIdentity.Create(navigationToDependentName), principalEntityType, dependentEntityType, configurationSource); /// <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> public virtual InternalForeignKeyBuilder? HasNavigations( MemberInfo? navigationToPrincipal, MemberInfo? navigationToDependent, EntityType principalEntityType, EntityType dependentEntityType, ConfigurationSource configurationSource) => HasNavigations( MemberIdentity.Create(navigationToPrincipal), MemberIdentity.Create(navigationToDependent), principalEntityType, dependentEntityType, configurationSource); private InternalForeignKeyBuilder? HasNavigations( MemberIdentity? navigationToPrincipal, MemberIdentity? navigationToDependent, EntityType principalEntityType, EntityType dependentEntityType, ConfigurationSource configurationSource) { var navigationToPrincipalName = navigationToPrincipal?.Name; var navigationToDependentName = navigationToDependent?.Name; if ((navigationToPrincipal == null || navigationToPrincipal.Value.Name == Metadata.DependentToPrincipal?.Name) && (navigationToDependent == null || navigationToDependent.Value.Name == Metadata.PrincipalToDependent?.Name)) { Metadata.UpdateConfigurationSource(configurationSource); if (navigationToPrincipal != null) { Metadata.SetDependentToPrincipal(navigationToPrincipal.Value.Name, configurationSource); if (navigationToPrincipalName != null) { dependentEntityType.RemoveIgnored(navigationToPrincipalName); } } if (navigationToDependent != null) { Metadata.SetPrincipalToDependent(navigationToDependent.Value.Name, configurationSource); if (navigationToDependentName != null) { principalEntityType.RemoveIgnored(navigationToDependentName); } } return this; } var shouldThrow = configurationSource == ConfigurationSource.Explicit; if (navigationToPrincipalName != null && navigationToPrincipal!.Value.MemberInfo == null && dependentEntityType.ClrType != Model.DefaultPropertyBagType) { var navigationProperty = FindCompatibleClrMember( navigationToPrincipalName, dependentEntityType, principalEntityType, shouldThrow); if (navigationProperty != null) { navigationToPrincipal = MemberIdentity.Create(navigationProperty); } } if (navigationToDependentName != null && navigationToDependent!.Value.MemberInfo == null && principalEntityType.ClrType != Model.DefaultPropertyBagType) { var navigationProperty = FindCompatibleClrMember( navigationToDependentName, principalEntityType, dependentEntityType, shouldThrow); if (navigationProperty != null) { navigationToDependent = MemberIdentity.Create(navigationProperty); } } if (!CanSetNavigations( navigationToPrincipal, navigationToDependent, principalEntityType, dependentEntityType, configurationSource, shouldThrow, out var shouldInvert, out var shouldBeUnique, out var removeOppositeNavigation, out var conflictingNavigationsFound, out var changeRelatedTypes)) { return null; } if (removeOppositeNavigation) { navigationToPrincipal ??= MemberIdentity.None; navigationToDependent ??= MemberIdentity.None; } IReadOnlyList<Property>? dependentProperties = null; IReadOnlyList<Property>? principalProperties = null; if (shouldInvert == true) { Check.DebugAssert( configurationSource.Overrides(Metadata.GetPropertiesConfigurationSource()), "configurationSource does not override Metadata.GetPropertiesConfigurationSource"); Check.DebugAssert( configurationSource.Overrides(Metadata.GetPrincipalKeyConfigurationSource()), "configurationSource does not override Metadata.GetPrincipalKeyConfigurationSource"); (principalEntityType, dependentEntityType) = (dependentEntityType, principalEntityType); (navigationToPrincipal, navigationToDependent) = (navigationToDependent, navigationToPrincipal); navigationToPrincipalName = navigationToPrincipal?.Name; navigationToDependentName = navigationToDependent?.Name; if (Metadata.GetPropertiesConfigurationSource() == configurationSource) { dependentProperties = []; } if (Metadata.GetPrincipalKeyConfigurationSource() == configurationSource) { principalProperties = []; } } if (navigationToPrincipalName != null && !dependentEntityType.FindNavigationsInHierarchy(navigationToPrincipalName).Any()) { dependentEntityType.Builder.RemoveMembersInHierarchy(navigationToPrincipalName, configurationSource); } if (navigationToDependentName != null && !principalEntityType.FindNavigationsInHierarchy(navigationToDependentName).Any()) { principalEntityType.Builder.RemoveMembersInHierarchy(navigationToDependentName, configurationSource); } InternalForeignKeyBuilder? builder; if (shouldInvert == true || conflictingNavigationsFound || changeRelatedTypes) { builder = ReplaceForeignKey( configurationSource, principalEntityType.Builder, dependentEntityType.Builder, navigationToPrincipal, navigationToDependent, dependentProperties, principalProperties: principalProperties, isUnique: shouldBeUnique, removeCurrent: shouldInvert == true || changeRelatedTypes, principalEndConfigurationSource: shouldInvert != null ? configurationSource : null, oldRelationshipInverted: shouldInvert == true); if (builder == null) { return null; } Check.DebugAssert(builder.Metadata.IsInModel, "builder.Metadata isn't in the model"); } else { using var batch = Metadata.DeclaringEntityType.Model.DelayConventions(); builder = this; if (navigationToPrincipal != null) { if (navigationToPrincipal.Value.Name == Metadata.PrincipalToDependent?.Name) { Metadata.SetPrincipalToDependent((string?)null, configurationSource); } var navigationProperty = navigationToPrincipal.Value.MemberInfo; if (navigationToPrincipalName != null) { Metadata.DeclaringEntityType.RemoveIgnored(navigationToPrincipalName); if (Metadata.DeclaringEntityType.ClrType != Model.DefaultPropertyBagType && navigationProperty == null) { throw new InvalidOperationException( CoreStrings.NoClrNavigation(navigationToPrincipalName, Metadata.DeclaringEntityType.DisplayName())); } } Metadata.SetDependentToPrincipal(navigationToPrincipal, configurationSource); } if (navigationToDependent != null) { // TODO: Use layering instead, issue #15898 IsUnique(shouldBeUnique, shouldBeUnique.HasValue ? configurationSource : ConfigurationSource.Convention); var navigationProperty = navigationToDependent.Value.MemberInfo; if (navigationToDependentName != null) { Metadata.PrincipalEntityType.RemoveIgnored(navigationToDependentName); if (Metadata.PrincipalEntityType.ClrType != Model.DefaultPropertyBagType && navigationProperty == null) { throw new InvalidOperationException( CoreStrings.NoClrNavigation(navigationToDependentName, Metadata.PrincipalEntityType.DisplayName())); } } Metadata.SetPrincipalToDependent(navigationToDependent, configurationSource); } builder = batch.Run(builder); } return builder != null && ((navigationToPrincipal != null && builder.Metadata.DependentToPrincipal?.Name != navigationToPrincipal.Value.Name) || (navigationToDependent != null && builder.Metadata.PrincipalToDependent?.Name != navigationToDependent.Value.Name)) && ((navigationToDependent != null && builder.Metadata.DependentToPrincipal?.Name != navigationToDependent.Value.Name) || (navigationToPrincipal != null && builder.Metadata.PrincipalToDependent?.Name != navigationToPrincipal.Value.Name)) ? null : 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> public static MemberInfo? FindCompatibleClrMember( string navigationName, EntityType sourceType, EntityType targetType, bool shouldThrow = false) { var navigationProperty = sourceType.GetNavigationMemberInfo(navigationName); return !Navigation.IsCompatible(navigationName, navigationProperty, sourceType, targetType, null, shouldThrow) ? null : navigationProperty; } /// <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> public virtual bool CanSetNavigation( MemberInfo? property, bool pointsToPrincipal, ConfigurationSource? configurationSource) => CanSetNavigation( MemberIdentity.Create(property), pointsToPrincipal, configurationSource, shouldThrow: false, out _); /// <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> public virtual bool CanSetNavigation( string? name, bool pointsToPrincipal, ConfigurationSource? configurationSource) => CanSetNavigation( MemberIdentity.Create(name), pointsToPrincipal, configurationSource, shouldThrow: false, out _); private bool CanSetNavigation( MemberIdentity navigation, bool pointsToPrincipal, ConfigurationSource? configurationSource, bool shouldThrow, out bool? shouldBeUnique) => pointsToPrincipal ? CanSetNavigations( navigation, navigationToDependent: null, configurationSource, shouldThrow, out shouldBeUnique) : CanSetNavigations( navigationToPrincipal: null, navigation, configurationSource, shouldThrow, out shouldBeUnique); /// <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> public virtual bool CanSetNavigations( MemberInfo? navigationToPrincipal, MemberInfo? navigationToDependent, ConfigurationSource? configurationSource) => CanSetNavigations( MemberIdentity.Create(navigationToPrincipal), MemberIdentity.Create(navigationToDependent), configurationSource, shouldThrow: false, out _); /// <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> public virtual bool CanSetNavigations( string? navigationToPrincipalName, string? navigationToDependentName, ConfigurationSource? configurationSource) => CanSetNavigations( MemberIdentity.Create(navigationToPrincipalName), MemberIdentity.Create(navigationToDependentName), configurationSource, shouldThrow: false, out _); private bool CanSetNavigations( MemberIdentity? navigationToPrincipal, MemberIdentity? navigationToDependent, ConfigurationSource? configurationSource) => CanSetNavigations( navigationToPrincipal, navigationToDependent, configurationSource, shouldThrow: false, out _); private bool CanSetNavigations( MemberIdentity? navigationToPrincipal, MemberIdentity? navigationToDependent, ConfigurationSource? configurationSource, bool shouldThrow, out bool? shouldBeUnique) => CanSetNavigations( navigationToPrincipal, navigationToDependent, Metadata.PrincipalEntityType, Metadata.DeclaringEntityType, configurationSource, shouldThrow, out _, out shouldBeUnique, out _, out _, out _); private bool CanSetNavigations( MemberIdentity? navigationToPrincipal, MemberIdentity? navigationToDependent, EntityType principalEntityType, EntityType dependentEntityType, ConfigurationSource? configurationSource, bool shouldThrow, out bool? shouldInvert, out bool? shouldBeUnique, out bool removeOppositeNavigation, out bool conflictingNavigationsFound, out bool changeRelatedTypes) { shouldInvert = null; shouldBeUnique = null; removeOppositeNavigation = false; conflictingNavigationsFound = false; changeRelatedTypes = false; if ((navigationToPrincipal == null || navigationToPrincipal.Value.Name == Metadata.DependentToPrincipal?.Name) && (navigationToDependent == null || navigationToDependent.Value.Name == Metadata.PrincipalToDependent?.Name)) { return true; } if (!configurationSource.HasValue) { return false; } var navigationToPrincipalName = navigationToPrincipal?.Name; if (navigationToPrincipal != null && navigationToPrincipalName != Metadata.DependentToPrincipal?.Name) { if (!configurationSource.Overrides(Metadata.GetDependentToPrincipalConfigurationSource())) { return false; } if (navigationToPrincipalName != null) { if (navigationToDependent == null && navigationToPrincipalName == Metadata.PrincipalToDependent?.Name && (Metadata.DeclaringEntityType.IsAssignableFrom(Metadata.PrincipalEntityType) || Metadata.PrincipalEntityType.IsAssignableFrom(Metadata.DeclaringEntityType))) { if (!configurationSource.Value.Overrides(Metadata.GetPrincipalToDependentConfigurationSource())) { return false; } removeOppositeNavigation = true; } else if ((configurationSource != ConfigurationSource.Explicit || !shouldThrow) && (!dependentEntityType.Builder.CanAddNavigation( navigationToPrincipalName, navigationToPrincipal.Value.MemberInfo?.GetMemberType(), configurationSource.Value))) { return false; } } } var navigationToDependentName = navigationToDependent?.Name; if (navigationToDependent != null && navigationToDependentName != Metadata.PrincipalToDependent?.Name) { if (!configurationSource.Overrides(Metadata.GetPrincipalToDependentConfigurationSource())) { return false; } if (navigationToDependentName != null) { if (navigationToPrincipal == null && navigationToDependentName == Metadata.DependentToPrincipal?.Name && (Metadata.DeclaringEntityType.IsAssignableFrom(Metadata.PrincipalEntityType) || Metadata.PrincipalEntityType.IsAssignableFrom(Metadata.DeclaringEntityType))) { if (!configurationSource.Value.Overrides(Metadata.GetDependentToPrincipalConfigurationSource())) { return false; } removeOppositeNavigation = true; } else if ((configurationSource != ConfigurationSource.Explicit || !shouldThrow) && (!principalEntityType.Builder.CanAddNavigation( navigationToDependentName, navigationToDependent.Value.MemberInfo?.GetMemberType(), configurationSource.Value))) { return false; } } } var navigationToPrincipalProperty = navigationToPrincipal?.MemberInfo; var navigationToDependentProperty = navigationToDependent?.MemberInfo; if (!AreCompatible( navigationToPrincipalProperty, navigationToDependentProperty, principalEntityType, dependentEntityType, shouldThrow, out shouldInvert, out shouldBeUnique)) { return false; } if (shouldBeUnique.HasValue && Metadata.IsUnique != shouldBeUnique && !configurationSource.Overrides(Metadata.GetIsUniqueConfigurationSource())) { return false; } var compatibleRelationship = FindCompatibleRelationship( principalEntityType, dependentEntityType, navigationToPrincipal, navigationToDependent, null, null, Metadata.GetPrincipalEndConfigurationSource(), configurationSource, out _, out var conflictingRelationshipsFound, out var resolvableRelationships); if (conflictingRelationshipsFound) { return false; } conflictingNavigationsFound = compatibleRelationship != null || resolvableRelationships.Any(r => (r.Resolution & (Resolution.ResetToDependent | Resolution.ResetToPrincipal | Resolution.Remove)) != 0); if (shouldBeUnique == null && (Metadata.IsUnique || configurationSource.OverridesStrictly(Metadata.GetIsUniqueConfigurationSource())) && ((navigationToDependentProperty != null && shouldInvert != true) || (navigationToPrincipalProperty != null && shouldInvert == true))) { // if new dependent can be both assume single shouldBeUnique = true; } if (shouldInvert == false && !conflictingNavigationsFound && (principalEntityType != Metadata.PrincipalEntityType || dependentEntityType != Metadata.DeclaringEntityType)) { if (navigationToPrincipalProperty != null && !IsCompatible( navigationToPrincipalProperty, pointsToPrincipal: true, Metadata.DeclaringEntityType, Metadata.PrincipalEntityType, shouldThrow: false, out _)) { changeRelatedTypes = true; return true; } if (navigationToDependentProperty != null && !IsCompatible( navigationToDependentProperty, pointsToPrincipal: false, Metadata.DeclaringEntityType, Metadata.PrincipalEntityType, shouldThrow: false, out _)) { changeRelatedTypes = true; return true; } } return true; } private bool CanRemoveNavigation(bool pointsToPrincipal, ConfigurationSource? configurationSource, bool overrideSameSource = true) => pointsToPrincipal ? Metadata.DependentToPrincipal == null || (configurationSource.Overrides(Metadata.GetDependentToPrincipalConfigurationSource()) && (overrideSameSource || configurationSource != Metadata.GetDependentToPrincipalConfigurationSource())) : Metadata.PrincipalToDependent == null || (!Metadata.IsOwnership && configurationSource.Overrides(Metadata.GetPrincipalToDependentConfigurationSource()) && (overrideSameSource || configurationSource != Metadata.GetPrincipalToDependentConfigurationSource())); /// <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> public static bool AreCompatible( MemberInfo? navigationToPrincipalProperty, MemberInfo? navigationToDependentProperty, EntityType principalEntityType, EntityType dependentEntityType, bool shouldThrow, out bool? shouldInvert, out bool? shouldBeUnique) { shouldInvert = null; shouldBeUnique = null; bool? invertedShouldBeUnique = null; if (navigationToPrincipalProperty != null && !IsCompatible( navigationToPrincipalProperty, pointsToPrincipal: false, principalEntityType, dependentEntityType, shouldThrow: false, out invertedShouldBeUnique)) { shouldInvert = false; } if (navigationToDependentProperty != null && !IsCompatible( navigationToDependentProperty, pointsToPrincipal: true, principalEntityType, dependentEntityType, shouldThrow: false, out _)) { shouldInvert = false; } if (navigationToPrincipalProperty != null && !IsCompatible( navigationToPrincipalProperty, pointsToPrincipal: true, dependentEntityType, principalEntityType, shouldThrow && shouldInvert != null, out _)) { if (shouldInvert != null) { return false; } shouldInvert = true; } if (navigationToDependentProperty != null && !IsCompatible( navigationToDependentProperty, pointsToPrincipal: false, dependentEntityType, principalEntityType, shouldThrow && shouldInvert != null, out shouldBeUnique)) { if (shouldInvert != null) { return false; } shouldInvert = true; } if (shouldInvert == true) { shouldBeUnique = invertedShouldBeUnique; } return true; } private static bool IsCompatible( MemberInfo navigationMember, bool pointsToPrincipal, EntityType dependentType, EntityType principalType, bool shouldThrow, out bool? shouldBeUnique) { shouldBeUnique = null; if (!pointsToPrincipal) { var canBeUnique = Navigation.IsCompatible( navigationMember.Name, navigationMember, principalType, dependentType, shouldBeCollection: false, shouldThrow: false); var canBeNonUnique = Navigation.IsCompatible( navigationMember.Name, navigationMember, principalType, dependentType, shouldBeCollection: true, shouldThrow: false); if (canBeUnique != canBeNonUnique) { shouldBeUnique = canBeUnique; } else if (!canBeUnique) { if (shouldThrow) { Navigation.IsCompatible( navigationMember.Name, navigationMember, principalType, dependentType, shouldBeCollection: null, shouldThrow: true); } return false; } } else if (!Navigation.IsCompatible( navigationMember.Name, navigationMember, dependentType, principalType, shouldBeCollection: false, shouldThrow)) { return false; } return true; } /// <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> public virtual InternalForeignKeyBuilder? IsRequired(bool? required, ConfigurationSource configurationSource) { if (!CanSetIsRequired(required, configurationSource)) { return null; } if (required == true && Metadata.GetPrincipalEndConfigurationSource() == null && configurationSource == ConfigurationSource.Explicit) { Metadata.DeclaringEntityType.Model.ScopedModelDependencies?.Logger.AmbiguousEndRequiredWarning(Metadata); } IConventionForeignKey? foreignKey = Metadata; Metadata.DeclaringEntityType.Model.ConventionDispatcher.Track( () => Metadata.SetIsRequired(required, configurationSource), ref foreignKey); return foreignKey != null ? ((ForeignKey)foreignKey).Builder : this; } /// <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> public virtual bool CanSetIsRequired(bool? required, ConfigurationSource? configurationSource) => Metadata.IsRequired == required || configurationSource.Overrides(Metadata.GetIsRequiredConfigurationSource()); /// <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> public virtual InternalForeignKeyBuilder? IsRequiredDependent(bool? required, ConfigurationSource configurationSource) { if (!CanSetIsRequiredDependent(required, configurationSource)) { return null; } if (required == true && Metadata.GetPrincipalEndConfigurationSource() == null && configurationSource == ConfigurationSource.Explicit) { throw new InvalidOperationException( CoreStrings.AmbiguousEndRequiredDependent( Metadata.Properties.Format(), Metadata.DeclaringEntityType.DisplayName())); } if (required == true && !Metadata.IsUnique) { IsUnique(null, configurationSource); } Metadata.SetIsRequiredDependent(required, configurationSource); return this; } /// <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> public virtual bool CanSetIsRequiredDependent(bool? required, ConfigurationSource? configurationSource) => Metadata.IsRequiredDependent == required || ((required != true || Metadata.IsUnique || configurationSource!.Value.Overrides(Metadata.GetIsUniqueConfigurationSource())) && configurationSource.Overrides(Metadata.GetIsRequiredDependentConfigurationSource())); /// <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> public virtual InternalForeignKeyBuilder? IsOwnership(bool? ownership, ConfigurationSource configurationSource) { if (Metadata.IsOwnership == ownership) { Metadata.SetIsOwnership(ownership, configurationSource); return this; } if (ownership == null || !configurationSource.Overrides(Metadata.GetIsOwnershipConfigurationSource())) { return null; } if (!ownership.Value) { Metadata.SetIsOwnership(ownership: false, configurationSource); return this; } if (!Metadata.DeclaringEntityType.Builder.CanSetIsOwned(true, configurationSource)) { return null; } var declaringType = Metadata.DeclaringEntityType; var newRelationshipBuilder = this; var otherOwnership = declaringType.GetDeclaredForeignKeys().SingleOrDefault(fk => fk.IsOwnership); var invertedOwnerships = declaringType.GetDeclaredReferencingForeignKeys() .Where(fk => fk.IsOwnership && fk.DeclaringEntityType.ClrType == Metadata.PrincipalEntityType.ClrType).ToList(); if (invertedOwnerships.Any(fk => !configurationSource.Overrides(fk.GetConfigurationSource()))) { return null; } if (declaringType.HasSharedClrType) { if (otherOwnership != null && !configurationSource.Overrides(otherOwnership.GetConfigurationSource())) { return null; } Metadata.SetIsOwnership(ownership: true, configurationSource); newRelationshipBuilder = newRelationshipBuilder.OnDelete(DeleteBehavior.Cascade, ConfigurationSource.Convention); if (newRelationshipBuilder == null) { return null; } if (otherOwnership?.IsInModel == true) { otherOwnership.DeclaringEntityType.Builder.HasNoRelationship(otherOwnership, configurationSource); } foreach (var invertedOwnership in invertedOwnerships) { if (invertedOwnership.IsInModel) { invertedOwnership.DeclaringEntityType.Builder.HasNoRelationship(invertedOwnership, configurationSource); } } newRelationshipBuilder.Metadata.DeclaringEntityType.Builder.IsOwned(true, configurationSource); return newRelationshipBuilder; } if (otherOwnership != null) { Check.DebugAssert( Metadata.DeclaringEntityType.IsOwned(), $"Expected {Metadata.DeclaringEntityType} to be owned"); if (!Metadata.GetConfigurationSource().Overrides(ConfigurationSource.Explicit) && Metadata.PrincipalEntityType.IsInOwnershipPath(Metadata.DeclaringEntityType.ClrType)) { return null; } Metadata.SetIsOwnership(ownership: true, configurationSource); using var batch = ModelBuilder.Metadata.DelayConventions(); newRelationshipBuilder = newRelationshipBuilder.OnDelete(DeleteBehavior.Cascade, ConfigurationSource.Convention); if (newRelationshipBuilder == null) { return null; } foreach (var invertedOwnership in invertedOwnerships) { invertedOwnership.DeclaringEntityType.Builder.HasNoRelationship(invertedOwnership, configurationSource); } var fk = newRelationshipBuilder.Metadata; fk.DeclaringEntityType.Builder.HasNoRelationship(fk, fk.GetConfigurationSource()); if (otherOwnership.Builder.MakeDeclaringTypeShared(configurationSource) == null) { return null; } var name = Metadata.PrincipalEntityType.GetOwnedName(declaringType.ShortName(), Metadata.PrincipalToDependent!.Name); var newEntityType = ModelBuilder.SharedTypeEntity( name, declaringType.ClrType, declaringType.GetConfigurationSource(), shouldBeOwned: true)!.Metadata; newRelationshipBuilder = newRelationshipBuilder.Attach(newEntityType.Builder)!; ModelBuilder.Metadata.ConventionDispatcher.Tracker.Update( Metadata, newRelationshipBuilder.Metadata); return batch.Run(newRelationshipBuilder); } using (var batch = ModelBuilder.Metadata.DelayConventions()) { var declaringEntityTypeBuilder = newRelationshipBuilder.Metadata.DeclaringEntityType.Builder.IsOwned(true, configurationSource, Metadata); Check.DebugAssert(declaringEntityTypeBuilder != null, "Expected declared type to be owned"); Metadata.SetIsOwnership(true, configurationSource); newRelationshipBuilder = newRelationshipBuilder.OnDelete(DeleteBehavior.Cascade, ConfigurationSource.Convention) ?? newRelationshipBuilder; foreach (var invertedOwnership in invertedOwnerships) { if (configurationSource.Overrides(invertedOwnership.DeclaringEntityType.GetConfigurationSource())) { ModelBuilder.HasNoEntityType(invertedOwnership.DeclaringEntityType, configurationSource); } else { invertedOwnership.DeclaringEntityType.Builder.HasNoRelationship(invertedOwnership, configurationSource); } } return batch.Run(newRelationshipBuilder); } } /// <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> public virtual bool CanSetIsOwnership(bool? ownership, ConfigurationSource? configurationSource) => (Metadata.IsOwnership == ownership || configurationSource.Overrides(Metadata.GetIsOwnershipConfigurationSource())) && (ownership != true || Metadata.DeclaringEntityType.IsOwned() || configurationSource.OverridesStrictly(Metadata.GetConfigurationSource())); /// <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> public virtual InternalForeignKeyBuilder? MakeDeclaringTypeShared(ConfigurationSource? configurationSource) { if (Metadata.DeclaringEntityType.HasSharedClrType) { return this; } if (configurationSource == null) { return null; } Check.DebugAssert(Metadata.IsOwnership, "Expected an ownership"); Check.DebugAssert(Metadata.PrincipalToDependent != null, "Expected a navigation to the dependent"); var name = Metadata.PrincipalEntityType.GetOwnedName( Metadata.DeclaringEntityType.ShortName(), Metadata.PrincipalToDependent.Name); var newEntityType = ModelBuilder.SharedTypeEntity( name, Metadata.DeclaringEntityType.ClrType, configurationSource.Value, shouldBeOwned: true)!.Metadata; var newOwnership = newEntityType.GetForeignKeys().SingleOrDefault(fk => fk.IsOwnership); if (newOwnership == null) { return Metadata.IsInModel ? Metadata.Builder : null; } Check.DebugAssert(!Metadata.IsInModel, "Metadata is in the model"); ModelBuilder.Metadata.ConventionDispatcher.Tracker.Update(Metadata, newOwnership); return newOwnership.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> public virtual InternalForeignKeyBuilder? OnDelete(DeleteBehavior? deleteBehavior, ConfigurationSource configurationSource) { if (!CanSetDeleteBehavior(deleteBehavior, configurationSource)) { return null; } Metadata.SetDeleteBehavior(deleteBehavior, configurationSource); return this; } /// <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> public virtual bool CanSetDeleteBehavior(DeleteBehavior? deleteBehavior, ConfigurationSource? configurationSource) => Metadata.DeleteBehavior == deleteBehavior || configurationSource.Overrides(Metadata.GetDeleteBehaviorConfigurationSource()); /// <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> public virtual InternalForeignKeyBuilder? IsUnique(bool? unique, ConfigurationSource configurationSource) { if (Metadata.IsUnique == unique) { Metadata.SetIsUnique(unique, configurationSource); return this; } if (!CanSetIsUnique(unique, configurationSource, out var resetToDependent)) { return null; } if (resetToDependent && Metadata.PrincipalToDependent!.GetConfigurationSource() == ConfigurationSource.Explicit) { throw new InvalidOperationException( CoreStrings.UnableToSetIsUnique( unique, Metadata.PrincipalToDependent.PropertyInfo!.Name, Metadata.PrincipalEntityType.DisplayName())); } using var batch = Metadata.DeclaringEntityType.Model.DelayConventions(); var builder = this; if (resetToDependent) { builder = builder.HasNavigations(navigationToPrincipal: null, MemberIdentity.None, configurationSource); if (builder == null) { return null; } } if (unique == false && Metadata.IsRequiredDependent) { builder.IsRequiredDependent(null, configurationSource); } builder.Metadata.SetIsUnique(unique, configurationSource); return batch.Run(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> public virtual bool CanSetIsUnique(bool? unique, ConfigurationSource? configurationSource) => CanSetIsUnique(unique, configurationSource, out _); private bool CanSetIsUnique(bool? unique, ConfigurationSource? configurationSource, out bool resetToDependent) { resetToDependent = false; if (Metadata.IsUnique == unique) { return true; } if (!configurationSource.HasValue || !configurationSource.Value.Overrides(Metadata.GetIsUniqueConfigurationSource())) { return false; } if (unique == false && Metadata.IsRequiredDependent && !configurationSource.Value.Overrides(Metadata.GetIsRequiredDependentConfigurationSource())) { return false; } var navigationMember = Metadata.PrincipalToDependent?.GetIdentifyingMemberInfo(); if (navigationMember != null && !Navigation.IsCompatible( Metadata.PrincipalToDependent!.Name, navigationMember, Metadata.PrincipalEntityType, Metadata.DeclaringEntityType, !unique, shouldThrow: false)) { if (!configurationSource.Value.Overrides(Metadata.GetPrincipalToDependentConfigurationSource())) { return false; } resetToDependent = true; } return true; } // Note: This will not invert relationships, use RelatedEntityTypes for that /// <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> public virtual InternalForeignKeyBuilder? DependentEntityType( EntityType dependentEntityType, ConfigurationSource configurationSource) { Check.NotNull(dependentEntityType); var builder = this; if (Metadata.DeclaringEntityType.IsAssignableFrom(dependentEntityType)) { if (Metadata.GetPrincipalEndConfigurationSource()?.Overrides(configurationSource) != true) { Metadata.UpdatePrincipalEndConfigurationSource(configurationSource); builder = (InternalForeignKeyBuilder?)ModelBuilder.Metadata.ConventionDispatcher.OnForeignKeyPrincipalEndChanged(builder); } return builder; } return dependentEntityType.IsAssignableFrom(Metadata.DeclaringEntityType) || configurationSource == ConfigurationSource.Explicit ? HasEntityTypes(Metadata.PrincipalEntityType, dependentEntityType, configurationSource) : null; } // Note: This will not invert relationships, use RelatedEntityTypes for that /// <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> public virtual InternalForeignKeyBuilder? PrincipalEntityType( EntityType principalEntityType, ConfigurationSource configurationSource) { Check.NotNull(principalEntityType); var builder = this; if (Metadata.PrincipalEntityType.IsAssignableFrom(principalEntityType)) { if (Metadata.GetPrincipalEndConfigurationSource()?.Overrides(configurationSource) != true) { Metadata.UpdatePrincipalEndConfigurationSource(configurationSource); builder = (InternalForeignKeyBuilder?)ModelBuilder.Metadata.ConventionDispatcher.OnForeignKeyPrincipalEndChanged(builder); } return builder; } return principalEntityType.IsAssignableFrom(Metadata.PrincipalEntityType) || configurationSource == ConfigurationSource.Explicit ? HasEntityTypes(principalEntityType, Metadata.DeclaringEntityType, configurationSource) : null; } /// <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> public virtual InternalForeignKeyBuilder? HasEntityTypes( EntityType principalEntityType, EntityType dependentEntityType, ConfigurationSource configurationSource) => HasEntityTypes(principalEntityType, dependentEntityType, configurationSource, configurationSource); private InternalForeignKeyBuilder? HasEntityTypes( EntityType principalEntityType, EntityType dependentEntityType, ConfigurationSource? principalEndConfigurationSource, ConfigurationSource configurationSource) { if ((Metadata.PrincipalEntityType == principalEntityType && Metadata.DeclaringEntityType == dependentEntityType) || (Metadata.PrincipalEntityType == principalEntityType.LeastDerivedType(Metadata.PrincipalEntityType) && Metadata.DeclaringEntityType == dependentEntityType.LeastDerivedType(Metadata.DeclaringEntityType))) { if (!principalEndConfigurationSource.HasValue || Metadata.GetPrincipalEndConfigurationSource()?.Overrides(principalEndConfigurationSource) == true) { return this; } Metadata.UpdatePrincipalEndConfigurationSource(principalEndConfigurationSource.Value); principalEntityType.UpdateConfigurationSource(configurationSource); dependentEntityType.UpdateConfigurationSource(configurationSource); return (InternalForeignKeyBuilder?)ModelBuilder.Metadata.ConventionDispatcher.OnForeignKeyPrincipalEndChanged(this); } if (!CanSetRelatedTypes( principalEntityType, dependentEntityType, strictPrincipal: true, navigationToPrincipal: null, navigationToDependent: null, configurationSource, shouldThrow: true, out var shouldInvert, out var shouldResetToPrincipal, out var shouldResetToDependent, out var shouldResetPrincipalProperties, out var shouldResetDependentProperties, out var shouldBeUnique) && configurationSource != ConfigurationSource.Explicit) { return null; } var dependentProperties = (IReadOnlyList<Property>) []; var principalProperties = (IReadOnlyList<Property>) []; var builder = this; if (shouldInvert) { Check.DebugAssert( configurationSource.Overrides(Metadata.GetPropertiesConfigurationSource()), "configurationSource does not override Metadata.GetPropertiesConfigurationSource"); Check.DebugAssert( configurationSource.Overrides(Metadata.GetPrincipalKeyConfigurationSource()), "configurationSource does not override Metadata.GetPrincipalKeyConfigurationSource"); principalEntityType = principalEntityType.LeastDerivedType(Metadata.DeclaringEntityType)!; dependentEntityType = dependentEntityType.LeastDerivedType(Metadata.PrincipalEntityType)!; } else { principalEntityType = principalEntityType.LeastDerivedType(Metadata.PrincipalEntityType)!; dependentEntityType = dependentEntityType.LeastDerivedType(Metadata.DeclaringEntityType)!; dependentProperties = shouldResetDependentProperties ? dependentProperties : ((Metadata.GetPropertiesConfigurationSource()?.Overrides(configurationSource) ?? false) ? dependentEntityType.Builder.GetActualProperties(Metadata.Properties, configurationSource) : null); principalProperties = shouldResetPrincipalProperties ? principalProperties : ((Metadata.GetPrincipalKeyConfigurationSource()?.Overrides(configurationSource) ?? false) ? principalEntityType.Builder.GetActualProperties(Metadata.PrincipalKey.Properties, configurationSource) : null); } return builder.ReplaceForeignKey( configurationSource, principalEntityType.Builder, dependentEntityType.Builder, shouldResetToPrincipal ? MemberIdentity.None : null, shouldResetToDependent ? MemberIdentity.None : null, dependentProperties, principalProperties: principalProperties, isUnique: shouldBeUnique, removeCurrent: true, principalEndConfigurationSource: principalEndConfigurationSource, oldRelationshipInverted: shouldInvert); } /// <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> public virtual bool CanSetEntityTypes( EntityType principalEntityType, EntityType dependentEntityType, ConfigurationSource? configurationSource) => CanSetEntityTypes( principalEntityType, dependentEntityType, configurationSource, out _, out _); /// <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> public virtual bool CanSetEntityTypes( EntityType principalEntityType, EntityType dependentEntityType, ConfigurationSource? configurationSource, out bool shouldResetToPrincipal, out bool shouldResetToDependent) => CanSetRelatedTypes( principalEntityType, dependentEntityType, strictPrincipal: true, navigationToPrincipal: null, navigationToDependent: null, configurationSource, shouldThrow: false, out _, out shouldResetToPrincipal, out shouldResetToDependent, out _, out _, out _); /// <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> public virtual bool CanInvert( IReadOnlyList<Property>? newForeignKeyProperties, ConfigurationSource? configurationSource) => configurationSource.Overrides(Metadata.GetPrincipalEndConfigurationSource()) && ((newForeignKeyProperties == null) || CanSetForeignKey(newForeignKeyProperties, Metadata.PrincipalEntityType, configurationSource)); /// <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> public virtual InternalForeignKeyBuilder? ReuniquifyImplicitProperties(bool force) { if (!force && (Metadata.GetPropertiesConfigurationSource() != null || !Metadata.DeclaringEntityType.Builder .ShouldReuniquifyTemporaryProperties(Metadata))) { return Metadata.Builder; } var relationshipBuilder = this; using var batch = Metadata.DeclaringEntityType.Model.DelayConventions(); var temporaryProperties = Metadata.Properties.Where(p => (p.IsShadowProperty() || p.DeclaringType.IsPropertyBag && p.IsIndexerProperty()) && ConfigurationSource.Convention.Overrides(p.GetConfigurationSource())).ToList(); var keysToDetach = temporaryProperties.SelectMany(p => p.GetContainingKeys() .Where(k => ConfigurationSource.Convention.Overrides(k.GetConfigurationSource()))) .Distinct().ToList(); List<RelationshipSnapshot>? detachedRelationships = null; foreach (var key in keysToDetach) { foreach (var referencingForeignKey in key.GetReferencingForeignKeys().ToList()) { detachedRelationships ??= []; detachedRelationships.Add(InternalEntityTypeBuilder.DetachRelationship(referencingForeignKey)); } } var detachedKeys = InternalEntityTypeBuilder.DetachKeys(keysToDetach); var detachedIndexes = InternalEntityTypeBuilder.DetachIndexes( temporaryProperties.SelectMany(p => p.GetContainingIndexes()).Distinct()); relationshipBuilder = relationshipBuilder.HasForeignKey((IReadOnlyList<Property>?)null, ConfigurationSource.Convention)!; if (detachedIndexes != null) { foreach (var indexBuilderTuple in detachedIndexes) { indexBuilderTuple.Attach(indexBuilderTuple.Metadata.DeclaringEntityType.Builder); } } if (detachedKeys != null) { foreach (var (internalKeyBuilder, configurationSource) in detachedKeys) { internalKeyBuilder.Attach(Metadata.DeclaringEntityType.GetRootType().Builder, configurationSource); } } if (detachedRelationships != null) { foreach (var detachedRelationship in detachedRelationships) { detachedRelationship.Attach(); } } return batch.Run(relationshipBuilder); } /// <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> public virtual InternalForeignKeyBuilder? HasForeignKey( IReadOnlyList<MemberInfo>? properties, ConfigurationSource configurationSource) => HasForeignKey(properties, Metadata.DeclaringEntityType, configurationSource); /// <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> public virtual InternalForeignKeyBuilder? HasForeignKey( IReadOnlyList<string>? propertyNames, ConfigurationSource configurationSource) => HasForeignKey(propertyNames, Metadata.DeclaringEntityType, configurationSource); /// <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> public virtual InternalForeignKeyBuilder? HasForeignKey( IReadOnlyList<MemberInfo>? properties, EntityType dependentEntityType, ConfigurationSource configurationSource) { using var batch = Metadata.DeclaringEntityType.Model.DelayConventions(); var relationship = HasForeignKey( dependentEntityType.Builder.GetOrCreateProperties(properties, configurationSource), dependentEntityType, configurationSource); if (relationship == null) { return null; } return (InternalForeignKeyBuilder?)batch.Run(relationship.Metadata)?.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> public virtual InternalForeignKeyBuilder? HasForeignKey( IReadOnlyList<string>? propertyNames, EntityType dependentEntityType, ConfigurationSource configurationSource) { using var batch = Metadata.DeclaringEntityType.Model.DelayConventions(); var useDefaultType = Metadata.GetPrincipalKeyConfigurationSource() == null || (propertyNames != null && Metadata.PrincipalKey.Properties.Count != propertyNames.Count); var relationship = HasForeignKey( dependentEntityType.Builder.GetOrCreateProperties( propertyNames, configurationSource, Metadata.PrincipalKey.Properties, Metadata.GetIsRequiredConfigurationSource() != null && Metadata.IsRequired, useDefaultType), dependentEntityType, configurationSource); if (relationship == null) { return null; } return (InternalForeignKeyBuilder?)batch.Run(relationship.Metadata)?.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> public virtual InternalForeignKeyBuilder? HasForeignKey( IReadOnlyList<Property>? properties, ConfigurationSource configurationSource) => HasForeignKey(properties, Metadata.DeclaringEntityType, configurationSource); /// <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> public virtual InternalForeignKeyBuilder? HasForeignKey( IReadOnlyList<Property>? properties, EntityType dependentEntityType, ConfigurationSource configurationSource) { if (properties == null) { return !configurationSource.Overrides(Metadata.GetPropertiesConfigurationSource()) ? null : ReplaceForeignKey( configurationSource, dependentProperties: []); } properties = dependentEntityType.Builder.GetActualProperties(properties, configurationSource)!; if (Metadata.Properties.SequenceEqual(properties)) { Metadata.UpdateConfigurationSource(configurationSource); Metadata.UpdatePropertiesConfigurationSource(configurationSource); var builder = this; if (!Metadata.IsSelfReferencing() && Metadata.GetPrincipalEndConfigurationSource()?.Overrides(configurationSource) != true) { Metadata.UpdatePrincipalEndConfigurationSource(configurationSource); builder = (InternalForeignKeyBuilder?)ModelBuilder.Metadata.ConventionDispatcher.OnForeignKeyPrincipalEndChanged(builder); } return builder; } if (!CanSetForeignKey( properties, dependentEntityType, configurationSource, out var resetPrincipalKey)) { return null; } return ReplaceForeignKey( configurationSource, dependentEntityTypeBuilder: dependentEntityType.Builder, dependentProperties: properties, principalProperties: resetPrincipalKey ? [] : null, principalEndConfigurationSource: configurationSource, removeCurrent: !Property.AreCompatible(properties, Metadata.DeclaringEntityType)); } /// <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> public virtual bool CanSetForeignKey(IReadOnlyList<string>? propertyNames, ConfigurationSource? configurationSource) { if (propertyNames is not null && ((IReadOnlyEntityType)Metadata.DeclaringEntityType).FindProperties(propertyNames) is { } properties) { return CanSetForeignKey( properties, dependentEntityType: null, configurationSource, out _); } return configurationSource.Overrides(Metadata.GetPropertiesConfigurationSource()); } /// <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> public virtual bool CanSetForeignKey(IReadOnlyList<Property>? properties, ConfigurationSource? configurationSource) => CanSetForeignKey( properties, dependentEntityType: null, configurationSource, out _); private bool CanSetForeignKey( IReadOnlyList<IReadOnlyProperty>? properties, EntityType? dependentEntityType, ConfigurationSource? configurationSource, bool overrideSameSource = true) => CanSetForeignKey( properties, dependentEntityType, configurationSource, out _, overrideSameSource); private bool CanSetForeignKey( IReadOnlyList<IReadOnlyProperty>? properties, EntityType? dependentEntityType, ConfigurationSource? configurationSource, out bool resetPrincipalKey, bool overrideSameSource = true) { resetPrincipalKey = false; return properties != null && Metadata.Properties.SequenceEqual(properties) || CanSetForeignKey( properties, dependentEntityType, Metadata.PrincipalKey.Properties, Metadata.PrincipalEntityType, configurationSource, out resetPrincipalKey, overrideSameSource); } private bool CanSetForeignKey( IReadOnlyList<IReadOnlyProperty>? properties, EntityType? dependentEntityType, IReadOnlyList<Property> principalKeyProperties, EntityType principalEntityType, ConfigurationSource? configurationSource, out bool resetPrincipalKey, bool overrideSameSource = true) { resetPrincipalKey = false; if (!configurationSource.Overrides(Metadata.GetPropertiesConfigurationSource()) || (!overrideSameSource && configurationSource == Metadata.GetPropertiesConfigurationSource())) { return false; } if (properties == null) { return true; } dependentEntityType ??= Metadata.DeclaringEntityType; // FKs are not allowed to use properties from inherited keys since this could result in an ambiguous value space if (dependentEntityType.BaseType != null && !principalEntityType.IsAssignableFrom(dependentEntityType) && configurationSource != ConfigurationSource.Explicit // let it throw for explicit && properties.Any(p => p.GetContainingKeys().Any(k => k.DeclaringEntityType != dependentEntityType))) { return false; } if ((dependentEntityType != Metadata.DeclaringEntityType && dependentEntityType == Metadata.PrincipalEntityType) // Check if inverted || (properties.Count != 0 && !ForeignKey.AreCompatible( principalKeyProperties, properties, principalEntityType, dependentEntityType, shouldThrow: false))) { if (!configurationSource.HasValue || !configurationSource.Overrides(Metadata.GetPrincipalKeyConfigurationSource())) { return false; } resetPrincipalKey = true; } return true; } /// <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> public virtual InternalForeignKeyBuilder? HasPrincipalKey( IReadOnlyList<MemberInfo>? members, ConfigurationSource configurationSource) { using var batch = Metadata.DeclaringEntityType.Model.DelayConventions(); var relationship = HasPrincipalKey( Metadata.PrincipalEntityType.Builder.GetOrCreateProperties(members, configurationSource), configurationSource); return relationship is null ? null : (InternalForeignKeyBuilder?)batch.Run(relationship.Metadata)?.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> public virtual InternalForeignKeyBuilder? HasPrincipalKey( IReadOnlyList<string>? propertyNames, ConfigurationSource configurationSource) { using var batch = Metadata.DeclaringEntityType.Model.DelayConventions(); var relationship = HasPrincipalKey( Metadata.PrincipalEntityType.Builder.GetOrCreateProperties(propertyNames, configurationSource), configurationSource); return relationship is null ? null : (InternalForeignKeyBuilder?)batch.Run(relationship.Metadata)?.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> public virtual InternalForeignKeyBuilder? HasPrincipalKey( IReadOnlyList<Property>? properties, ConfigurationSource configurationSource) { if (properties == null) { return !configurationSource.Overrides(Metadata.GetPrincipalKeyConfigurationSource()) ? null : ReplaceForeignKey( configurationSource, principalProperties: []); } properties = Metadata.PrincipalEntityType.Builder.GetActualProperties(properties, configurationSource)!; if (Metadata.PrincipalKey.Properties.SequenceEqual(properties)) { Metadata.UpdateConfigurationSource(configurationSource); Metadata.UpdatePrincipalKeyConfigurationSource(configurationSource); var builder = this; if (!Metadata.IsSelfReferencing() && Metadata.GetPrincipalEndConfigurationSource()?.Overrides(configurationSource) != true) { Metadata.UpdatePrincipalEndConfigurationSource(configurationSource); builder = (InternalForeignKeyBuilder?)ModelBuilder.Metadata.ConventionDispatcher.OnForeignKeyPrincipalEndChanged(builder); } return builder; } if (!CanSetPrincipalKey(properties, configurationSource, out var resetDependent, out var oldNameDependentProperties)) { return null; } return ReplaceForeignKey( configurationSource, principalProperties: properties, dependentProperties: resetDependent ? [] : null, principalEndConfigurationSource: configurationSource, oldNameDependentProperties: oldNameDependentProperties, removeCurrent: oldNameDependentProperties != null); } /// <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> public virtual bool CanSetPrincipalKey(IReadOnlyList<string>? propertyNames, ConfigurationSource? configurationSource) { if (propertyNames is not null && ((IReadOnlyEntityType)Metadata.PrincipalEntityType).FindProperties(propertyNames) is { } properties) { return CanSetPrincipalKey( properties, configurationSource, out _, out _); } return configurationSource.Overrides(Metadata.GetPrincipalKeyConfigurationSource()); } /// <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> public virtual bool CanSetPrincipalKey(IReadOnlyList<Property>? properties, ConfigurationSource? configurationSource) => CanSetPrincipalKey( properties, configurationSource, out _, out _); private bool CanSetPrincipalKey( IReadOnlyList<IReadOnlyProperty>? properties, ConfigurationSource? configurationSource, out bool resetDependent, out IReadOnlyList<Property>? oldNameDependentProperties) { resetDependent = false; oldNameDependentProperties = null; if (properties is not null && Metadata.PrincipalKey.Properties.SequenceEqual(properties)) { return true; } if (!configurationSource.Overrides(Metadata.GetPrincipalKeyConfigurationSource())) { return false; } if (properties == null) { return true; } if (!ForeignKey.AreCompatible( properties, Metadata.Properties, Metadata.PrincipalEntityType, Metadata.DeclaringEntityType, shouldThrow: false)) { if (!configurationSource?.Overrides(Metadata.GetPropertiesConfigurationSource()) == true) { return false; } if (Metadata.GetPropertiesConfigurationSource().Overrides(ConfigurationSource.DataAnnotation) && Metadata.Properties.All(p => ConfigurationSource.Convention.Overrides(p.GetTypeConfigurationSource()) && (p.IsShadowProperty() || p.IsIndexerProperty()))) { oldNameDependentProperties = Metadata.Properties; } resetDependent = true; } return true; } private InternalForeignKeyBuilder? ReplaceForeignKey( ConfigurationSource configurationSource, InternalEntityTypeBuilder? principalEntityTypeBuilder = null, InternalEntityTypeBuilder? dependentEntityTypeBuilder = null, MemberIdentity? navigationToPrincipal = null, MemberIdentity? navigationToDependent = null, IReadOnlyList<Property>? dependentProperties = null, IReadOnlyList<Property>? oldNameDependentProperties = null, IReadOnlyList<Property>? principalProperties = null, bool? isUnique = null, bool? isRequired = null, bool? isRequiredDependent = null, bool? isOwnership = null, DeleteBehavior? deleteBehavior = null, bool removeCurrent = false, ConfigurationSource? principalEndConfigurationSource = null, bool oldRelationshipInverted = false) { if (oldRelationshipInverted && Metadata.IsRequired && Metadata.GetIsRequiredConfigurationSource() == ConfigurationSource.Explicit && Metadata.GetPrincipalEndConfigurationSource() == null) { throw new InvalidOperationException( CoreStrings.AmbiguousEndRequiredInverted( Metadata.Properties.Format(), Metadata.DeclaringEntityType.DisplayName(), Metadata.PrincipalEntityType.DisplayName())); } principalEntityTypeBuilder ??= (oldRelationshipInverted ? Metadata.DeclaringEntityType.Builder : Metadata.PrincipalEntityType.Builder); dependentEntityTypeBuilder ??= (oldRelationshipInverted ? Metadata.PrincipalEntityType.Builder : Metadata.DeclaringEntityType.Builder); if (navigationToPrincipal == null) { if (oldRelationshipInverted) { navigationToPrincipal = Metadata.GetPrincipalToDependentConfigurationSource()?.Overrides(configurationSource) ?? false ? Metadata.PrincipalToDependent.CreateMemberIdentity() : navigationToPrincipal; } else { navigationToPrincipal = Metadata.GetDependentToPrincipalConfigurationSource()?.Overrides(configurationSource) ?? false ? Metadata.DependentToPrincipal.CreateMemberIdentity() : navigationToPrincipal; } } if (navigationToDependent == null) { if (oldRelationshipInverted) { navigationToDependent = Metadata.GetDependentToPrincipalConfigurationSource()?.Overrides(configurationSource) ?? false ? Metadata.DependentToPrincipal.CreateMemberIdentity() : navigationToDependent; } else { navigationToDependent = Metadata.GetPrincipalToDependentConfigurationSource()?.Overrides(configurationSource) ?? false ? Metadata.PrincipalToDependent.CreateMemberIdentity() : navigationToDependent; } } dependentProperties ??= ((Metadata.GetPropertiesConfigurationSource()?.Overrides(configurationSource) ?? false) && !oldRelationshipInverted ? Metadata.Properties : null); principalProperties ??= ((Metadata.GetPrincipalKeyConfigurationSource()?.Overrides(configurationSource) ?? false) && !oldRelationshipInverted ? Metadata.PrincipalKey.Properties : null); isUnique ??= ((Metadata.GetIsUniqueConfigurationSource()?.Overrides(configurationSource) ?? false) ? Metadata.IsUnique : null); isRequired ??= !oldRelationshipInverted ? ((Metadata.GetIsRequiredConfigurationSource()?.Overrides(configurationSource) ?? false) ? Metadata.IsRequired : null) : ((Metadata.GetIsRequiredDependentConfigurationSource()?.Overrides(ConfigurationSource.Explicit) ?? false) ? Metadata.IsRequiredDependent : null); isRequiredDependent ??= !oldRelationshipInverted ? ((Metadata.GetIsRequiredDependentConfigurationSource()?.Overrides(configurationSource) ?? false) ? Metadata.IsRequiredDependent : null) : ((Metadata.GetIsRequiredConfigurationSource()?.Overrides(ConfigurationSource.Explicit) ?? false) ? Metadata.IsRequired : null); isOwnership ??= !oldRelationshipInverted && (Metadata.GetIsOwnershipConfigurationSource()?.Overrides(configurationSource) ?? false) ? Metadata.IsOwnership : null; deleteBehavior ??= ((Metadata.GetDeleteBehaviorConfigurationSource()?.Overrides(configurationSource) ?? false) ? Metadata.DeleteBehavior : null); principalEndConfigurationSource ??= (principalEntityTypeBuilder.Metadata != dependentEntityTypeBuilder.Metadata && ((principalProperties?.Count > 0) || (dependentProperties?.Count > 0) || (navigationToDependent != null && isUnique == false) || isOwnership == true) ? configurationSource : null); principalEndConfigurationSource = principalEndConfigurationSource.Max(Metadata.GetPrincipalEndConfigurationSource()); return ReplaceForeignKey( principalEntityTypeBuilder, dependentEntityTypeBuilder, navigationToPrincipal, navigationToDependent, dependentProperties, oldNameDependentProperties, principalProperties, isUnique, isRequired, isRequiredDependent, isOwnership, deleteBehavior, removeCurrent, oldRelationshipInverted, principalEndConfigurationSource, configurationSource); } private InternalForeignKeyBuilder? ReplaceForeignKey( InternalEntityTypeBuilder principalEntityTypeBuilder, InternalEntityTypeBuilder dependentEntityTypeBuilder, MemberIdentity? navigationToPrincipal, MemberIdentity? navigationToDependent, IReadOnlyList<Property>? dependentProperties, IReadOnlyList<Property>? oldNameDependentProperties, IReadOnlyList<Property>? principalProperties, bool? isUnique, bool? isRequired, bool? isRequiredDependent, bool? isOwnership, DeleteBehavior? deleteBehavior, bool removeCurrent, bool oldRelationshipInverted, ConfigurationSource? principalEndConfigurationSource, ConfigurationSource configurationSource) { Check.NotNull(principalEntityTypeBuilder); Check.NotNull(dependentEntityTypeBuilder); if (configurationSource == ConfigurationSource.Explicit && principalEntityTypeBuilder.Metadata.IsKeyless) { throw new InvalidOperationException( CoreStrings.PrincipalKeylessType( principalEntityTypeBuilder.Metadata.DisplayName(), principalEntityTypeBuilder.Metadata.DisplayName() + (navigationToDependent?.Name == null ? "" : "." + navigationToDependent.Value.Name), dependentEntityTypeBuilder.Metadata.DisplayName() + (navigationToPrincipal?.Name == null ? "" : "." + navigationToPrincipal.Value.Name))); } Check.DebugAssert( navigationToPrincipal?.Name == null || navigationToPrincipal.Value.MemberInfo != null || dependentEntityTypeBuilder.Metadata.ClrType == Model.DefaultPropertyBagType, "Principal navigation check failed"); Check.DebugAssert( navigationToDependent?.Name == null || navigationToDependent.Value.MemberInfo != null || principalEntityTypeBuilder.Metadata.ClrType == Model.DefaultPropertyBagType, "Dependent navigation check failed"); Check.DebugAssert( AreCompatible( principalEntityTypeBuilder.Metadata, dependentEntityTypeBuilder.Metadata, navigationToPrincipal?.MemberInfo, navigationToDependent?.MemberInfo, dependentProperties?.Count > 0 ? dependentProperties : null, principalProperties?.Count > 0 ? principalProperties : null, isUnique, configurationSource), "Compatibility check failed"); Check.DebugAssert( oldNameDependentProperties == null || (dependentProperties?.Count ?? 0) == 0, "Dependent properties check failed"); Check.DebugAssert( removeCurrent || !Metadata.IsInModel || (Metadata.PrincipalEntityType.IsAssignableFrom(principalEntityTypeBuilder.Metadata) && Metadata.DeclaringEntityType.IsAssignableFrom(dependentEntityTypeBuilder.Metadata)), "Entity type check failed"); using var batch = Metadata.DeclaringEntityType.Model.DelayConventions(); var referencingSkipNavigations = Metadata.ReferencingSkipNavigations ?.Select(n => (Navigation: n, ConfigurationSource: n.GetForeignKeyConfigurationSource()!.Value)).ToList(); var newRelationshipBuilder = GetOrCreateRelationshipBuilder( principalEntityTypeBuilder.Metadata, dependentEntityTypeBuilder.Metadata, navigationToPrincipal, navigationToDependent, dependentProperties?.Count > 0 ? dependentProperties : null, oldNameDependentProperties, principalProperties?.Count > 0 ? principalProperties : null, isRequired, removeCurrent, principalEndConfigurationSource, configurationSource, out var existingRelationshipInverted); if (newRelationshipBuilder == null) { return null; } var initialPrincipalEndConfigurationSource = newRelationshipBuilder.Metadata.GetPrincipalEndConfigurationSource(); var strictPrincipal = principalEndConfigurationSource.HasValue && principalEndConfigurationSource.Value.Overrides(initialPrincipalEndConfigurationSource); if (existingRelationshipInverted == true && !strictPrincipal) { oldRelationshipInverted = !oldRelationshipInverted; existingRelationshipInverted = false; (principalEntityTypeBuilder, dependentEntityTypeBuilder) = (dependentEntityTypeBuilder, principalEntityTypeBuilder); (navigationToPrincipal, navigationToDependent) = (navigationToDependent, navigationToPrincipal); dependentProperties = null; principalProperties = null; } var oldNavigationToPrincipal = oldRelationshipInverted ? Metadata.PrincipalToDependent : Metadata.DependentToPrincipal; var oldNavigationToDependent = oldRelationshipInverted ? Metadata.DependentToPrincipal : Metadata.PrincipalToDependent; var oldToPrincipalConfigurationSource = oldRelationshipInverted ? Metadata.GetPrincipalToDependentConfigurationSource() : Metadata.GetDependentToPrincipalConfigurationSource(); var oldToDependentConfigurationSource = oldRelationshipInverted ? Metadata.GetDependentToPrincipalConfigurationSource() : Metadata.GetPrincipalToDependentConfigurationSource(); var newRelationshipConfigurationSource = Metadata.GetConfigurationSource(); if ((dependentProperties?.Count > 0) || navigationToPrincipal?.Name != null || navigationToDependent?.Name != null) { newRelationshipConfigurationSource = newRelationshipConfigurationSource.Max(configurationSource); } newRelationshipBuilder.Metadata.UpdateConfigurationSource(newRelationshipConfigurationSource); var resetToPrincipal = newRelationshipBuilder.Metadata.DependentToPrincipal != null && ((existingRelationshipInverted == false && navigationToPrincipal != null && navigationToPrincipal.Value.Name != newRelationshipBuilder.Metadata.DependentToPrincipal.Name) || (existingRelationshipInverted == true && navigationToDependent != null && navigationToDependent.Value.Name != newRelationshipBuilder.Metadata.DependentToPrincipal.Name)); var resetToDependent = newRelationshipBuilder.Metadata.PrincipalToDependent != null && ((existingRelationshipInverted == false && navigationToDependent != null && navigationToDependent.Value.Name != newRelationshipBuilder.Metadata.PrincipalToDependent.Name) || (existingRelationshipInverted == true && navigationToPrincipal != null && navigationToPrincipal.Value.Name != newRelationshipBuilder.Metadata.PrincipalToDependent.Name)); if (resetToPrincipal || resetToDependent) { newRelationshipBuilder = newRelationshipBuilder.HasNavigations( resetToPrincipal ? MemberIdentity.None : null, resetToDependent ? MemberIdentity.None : null, configurationSource) ?? newRelationshipBuilder; } newRelationshipBuilder = newRelationshipBuilder.HasEntityTypes( principalEntityTypeBuilder.Metadata, dependentEntityTypeBuilder.Metadata, principalEndConfigurationSource, configurationSource) ?? newRelationshipBuilder; dependentProperties = oldNameDependentProperties ?? dependentProperties; if (dependentProperties != null || principalProperties != null) { var shouldSetProperties = false; ConfigurationSource? foreignKeyPropertiesConfigurationSource = null; if (dependentProperties != null) { dependentProperties = dependentEntityTypeBuilder.GetActualProperties(dependentProperties, configurationSource)!; foreignKeyPropertiesConfigurationSource = configurationSource; if (PropertyListComparer.Instance.Equals(Metadata.Properties, dependentProperties) && !oldRelationshipInverted) { foreignKeyPropertiesConfigurationSource = foreignKeyPropertiesConfigurationSource.Max(Metadata.GetPropertiesConfigurationSource()); } if (foreignKeyPropertiesConfigurationSource.HasValue) { if (newRelationshipBuilder.Metadata.Properties.SequenceEqual(dependentProperties)) { var updated = newRelationshipBuilder.HasForeignKey( dependentProperties, foreignKeyPropertiesConfigurationSource.Value); Check.DebugAssert(updated == newRelationshipBuilder, "updated != newRelationshipBuilder"); } else if (dependentProperties.Count > 0 || (!removeCurrent && Metadata == newRelationshipBuilder.Metadata)) { shouldSetProperties = true; } } } ConfigurationSource? principalKeyConfigurationSource = null; if (principalProperties != null) { principalProperties = principalEntityTypeBuilder.GetActualProperties(principalProperties, configurationSource)!; principalKeyConfigurationSource = configurationSource; if (PropertyListComparer.Instance.Equals( principalProperties, newRelationshipBuilder.Metadata.PrincipalKey.Properties) && !oldRelationshipInverted) { principalKeyConfigurationSource = principalKeyConfigurationSource.Max(Metadata.GetPrincipalKeyConfigurationSource()); } if (principalKeyConfigurationSource.HasValue) { if (newRelationshipBuilder.Metadata.PrincipalKey.Properties.SequenceEqual(principalProperties)) { var updated = newRelationshipBuilder.HasPrincipalKey( principalProperties, principalKeyConfigurationSource.Value); Check.DebugAssert(updated == newRelationshipBuilder, "updated != newRelationshipBuilder"); } else if (principalProperties.Count > 0 || (!removeCurrent && Metadata == newRelationshipBuilder.Metadata)) { shouldSetProperties = true; } } } if (shouldSetProperties) { Key? principalKey = null; if (principalProperties != null && principalProperties.Count != 0) { principalKey = principalEntityTypeBuilder.Metadata.GetRootType().Builder .HasKey(principalProperties, configurationSource)!.Metadata; } var foreignKey = newRelationshipBuilder.Metadata; newRelationshipBuilder = foreignKey.DeclaringEntityType.Builder.UpdateForeignKey( foreignKey, dependentProperties?.Count == 0 ? null : dependentProperties, principalKey, navigationToPrincipal?.Name ?? referencingSkipNavigations?.FirstOrDefault().Navigation?.Inverse?.Name, isRequired, configurationSource: null); if (newRelationshipBuilder == null) { return null; } if (foreignKeyPropertiesConfigurationSource != null && dependentProperties?.Count != 0) { newRelationshipBuilder.Metadata.UpdatePropertiesConfigurationSource( foreignKeyPropertiesConfigurationSource.Value); } if (principalKeyConfigurationSource != null && principalProperties!.Count != 0) { newRelationshipBuilder.Metadata.UpdatePrincipalKeyConfigurationSource( principalKeyConfigurationSource.Value); } } } if (isUnique.HasValue) { var isUniqueConfigurationSource = configurationSource; if (isUnique.Value == Metadata.IsUnique) { isUniqueConfigurationSource = isUniqueConfigurationSource.Max(Metadata.GetIsUniqueConfigurationSource()); } newRelationshipBuilder = newRelationshipBuilder.IsUnique( isUnique.Value, isUniqueConfigurationSource) ?? newRelationshipBuilder; } else if (!oldRelationshipInverted && Metadata.GetIsUniqueConfigurationSource() is { } isUniqueConfigurationSource && !newRelationshipBuilder.Metadata.GetIsUniqueConfigurationSource().HasValue) { newRelationshipBuilder = newRelationshipBuilder.IsUnique(Metadata.IsUnique, isUniqueConfigurationSource) ?? newRelationshipBuilder; } if (isRequired.HasValue) { var isRequiredConfigurationSource = configurationSource; if (isRequired.Value == Metadata.IsRequired) { isRequiredConfigurationSource = isRequiredConfigurationSource.Max(Metadata.GetIsRequiredConfigurationSource()); } newRelationshipBuilder = newRelationshipBuilder.IsRequired( isRequired.Value, isRequiredConfigurationSource) ?? newRelationshipBuilder; } else { if (!oldRelationshipInverted) { if (Metadata.GetIsRequiredConfigurationSource() is { } isRequiredConfigurationSource && !newRelationshipBuilder.Metadata.GetIsRequiredConfigurationSource().HasValue) { newRelationshipBuilder = newRelationshipBuilder.IsRequired( Metadata.IsRequired, isRequiredConfigurationSource) ?? newRelationshipBuilder; } } else { if (Metadata.GetIsRequiredDependentConfigurationSource() is { } isRequiredDependentConfigurationSource && isRequiredDependentConfigurationSource.Overrides(ConfigurationSource.Explicit) && !newRelationshipBuilder.Metadata.GetIsRequiredConfigurationSource().HasValue) { newRelationshipBuilder = newRelationshipBuilder.IsRequired( Metadata.IsRequiredDependent, isRequiredDependentConfigurationSource) ?? newRelationshipBuilder; } } } if (isRequiredDependent.HasValue) { var isRequiredDependentConfigurationSource = configurationSource; if (isRequiredDependent.Value == Metadata.IsRequiredDependent) { isRequiredDependentConfigurationSource = isRequiredDependentConfigurationSource.Max( Metadata.GetIsRequiredDependentConfigurationSource()); } newRelationshipBuilder = newRelationshipBuilder.IsRequiredDependent( isRequiredDependent.Value, isRequiredDependentConfigurationSource) ?? newRelationshipBuilder; } else { if (!oldRelationshipInverted) { if (Metadata.GetIsRequiredDependentConfigurationSource() is { } isRequiredDependentConfigurationSource && !newRelationshipBuilder.Metadata.GetIsRequiredDependentConfigurationSource().HasValue) { newRelationshipBuilder = newRelationshipBuilder.IsRequiredDependent( Metadata.IsRequiredDependent, isRequiredDependentConfigurationSource) ?? newRelationshipBuilder; } } else { if (Metadata.GetIsRequiredConfigurationSource() is { } isRequiredConfigurationSource && isRequiredConfigurationSource.Overrides(ConfigurationSource.Explicit) && !newRelationshipBuilder.Metadata.GetIsRequiredDependentConfigurationSource().HasValue) { newRelationshipBuilder = newRelationshipBuilder.IsRequiredDependent( Metadata.IsRequired, isRequiredConfigurationSource) ?? newRelationshipBuilder; } } } if (deleteBehavior.HasValue) { var deleteBehaviorConfigurationSource = configurationSource; if (deleteBehavior.Value == Metadata.DeleteBehavior) { deleteBehaviorConfigurationSource = deleteBehaviorConfigurationSource.Max(Metadata.GetDeleteBehaviorConfigurationSource()); } newRelationshipBuilder = newRelationshipBuilder.OnDelete( deleteBehavior.Value, deleteBehaviorConfigurationSource) ?? newRelationshipBuilder; } else if (!oldRelationshipInverted && Metadata.GetDeleteBehaviorConfigurationSource() is { } deleteBehaviorConfigurationSource && !newRelationshipBuilder.Metadata.GetDeleteBehaviorConfigurationSource().HasValue) { newRelationshipBuilder = newRelationshipBuilder.OnDelete( Metadata.DeleteBehavior, deleteBehaviorConfigurationSource) ?? newRelationshipBuilder; } if (navigationToPrincipal != null) { var navigationToPrincipalConfigurationSource = configurationSource; if (navigationToPrincipal.Value.Name == oldNavigationToPrincipal?.Name) { navigationToPrincipalConfigurationSource = navigationToPrincipalConfigurationSource.Max(oldToPrincipalConfigurationSource); } newRelationshipBuilder = newRelationshipBuilder.HasNavigations( navigationToPrincipal, navigationToDependent: null, navigationToPrincipalConfigurationSource) ?? newRelationshipBuilder; if (oldNavigationToPrincipal != null && newRelationshipBuilder.Metadata.DependentToPrincipal != null && oldNavigationToPrincipal != newRelationshipBuilder.Metadata.DependentToPrincipal) { newRelationshipBuilder = MergeFacetsFrom( newRelationshipBuilder.Metadata.DependentToPrincipal, oldNavigationToPrincipal); } } else if (oldNavigationToPrincipal != null && newRelationshipBuilder.Metadata.DependentToPrincipal == null && newRelationshipBuilder.CanSetNavigations( oldNavigationToPrincipal.CreateMemberIdentity(), navigationToDependent: null, oldToPrincipalConfigurationSource)) { newRelationshipBuilder = newRelationshipBuilder.HasNavigations( oldNavigationToPrincipal.CreateMemberIdentity(), navigationToDependent: null, oldToPrincipalConfigurationSource!.Value) ?? newRelationshipBuilder; if (newRelationshipBuilder.Metadata.DependentToPrincipal != null) { newRelationshipBuilder = MergeFacetsFrom( newRelationshipBuilder.Metadata.DependentToPrincipal, oldNavigationToPrincipal); } } if (navigationToDependent != null) { var navigationToDependentConfigurationSource = configurationSource; if (navigationToDependent.Value.Name == oldNavigationToDependent?.Name) { navigationToDependentConfigurationSource = navigationToDependentConfigurationSource.Max(oldToDependentConfigurationSource); } newRelationshipBuilder = newRelationshipBuilder.HasNavigations( navigationToPrincipal: null, navigationToDependent, navigationToDependentConfigurationSource) ?? newRelationshipBuilder; if (oldNavigationToDependent != null && newRelationshipBuilder.Metadata.PrincipalToDependent != null && oldNavigationToDependent != newRelationshipBuilder.Metadata.PrincipalToDependent) { newRelationshipBuilder = MergeFacetsFrom( newRelationshipBuilder.Metadata.PrincipalToDependent, oldNavigationToDependent); } } else if (oldNavigationToDependent != null && newRelationshipBuilder.Metadata.PrincipalToDependent == null && newRelationshipBuilder.CanSetNavigations( navigationToPrincipal: null, oldNavigationToDependent.CreateMemberIdentity(), oldToDependentConfigurationSource)) { newRelationshipBuilder = newRelationshipBuilder.HasNavigations( navigationToPrincipal: null, oldNavigationToDependent.CreateMemberIdentity(), oldToDependentConfigurationSource!.Value) ?? newRelationshipBuilder; if (newRelationshipBuilder.Metadata.PrincipalToDependent != null) { newRelationshipBuilder = MergeFacetsFrom( newRelationshipBuilder.Metadata.PrincipalToDependent, oldNavigationToDependent); } } if (isOwnership.HasValue) { var isOwnershipConfigurationSource = configurationSource; if (isOwnership.Value == Metadata.IsOwnership) { isOwnershipConfigurationSource = isOwnershipConfigurationSource.Max(Metadata.GetIsOwnershipConfigurationSource()); } newRelationshipBuilder = newRelationshipBuilder.IsOwnership( isOwnership.Value, isOwnershipConfigurationSource) ?? newRelationshipBuilder; } else if (!oldRelationshipInverted && Metadata.GetIsOwnershipConfigurationSource() is { } getIsOwnershipConfigurationSource) { newRelationshipBuilder = newRelationshipBuilder.IsOwnership( Metadata.IsOwnership, getIsOwnershipConfigurationSource) ?? newRelationshipBuilder; } if (referencingSkipNavigations != null) { foreach (var referencingNavigationTuple in referencingSkipNavigations) { var skipNavigation = referencingNavigationTuple.Navigation; if (!skipNavigation.IsInModel) { var navigationEntityType = skipNavigation.DeclaringEntityType; skipNavigation = !navigationEntityType.IsInModel ? null : navigationEntityType.FindSkipNavigation(skipNavigation.Name); } skipNavigation?.Builder.HasForeignKey( newRelationshipBuilder.Metadata, referencingNavigationTuple.ConfigurationSource); } } if (Metadata != newRelationshipBuilder.Metadata) { newRelationshipBuilder.MergeAnnotationsFrom(Metadata); } newRelationshipBuilder = batch.Run(newRelationshipBuilder); return newRelationshipBuilder; } private static InternalForeignKeyBuilder MergeFacetsFrom(Navigation newNavigation, Navigation oldNavigation) { newNavigation.Builder.MergeAnnotationsFrom(oldNavigation); var builder = newNavigation.Builder; var propertyAccessModeConfigurationSource = oldNavigation.GetPropertyAccessModeConfigurationSource(); if (propertyAccessModeConfigurationSource.HasValue && builder.CanSetPropertyAccessMode( ((IConventionNavigation)oldNavigation).GetPropertyAccessMode(), propertyAccessModeConfigurationSource)) { builder = builder.UsePropertyAccessMode( ((IConventionNavigation)oldNavigation).GetPropertyAccessMode(), propertyAccessModeConfigurationSource.Value)!; } var oldFieldInfoConfigurationSource = oldNavigation.GetFieldInfoConfigurationSource(); if (oldFieldInfoConfigurationSource.HasValue && builder.CanSetField(oldNavigation.FieldInfo, oldFieldInfoConfigurationSource)) { builder = builder.HasField(oldNavigation.FieldInfo, oldFieldInfoConfigurationSource.Value)!; } var oldIsEagerLoadedConfigurationSource = ((IConventionNavigation)oldNavigation).GetIsEagerLoadedConfigurationSource(); if (oldIsEagerLoadedConfigurationSource.HasValue && builder.CanSetAutoInclude(((IReadOnlyNavigation)oldNavigation).IsEagerLoaded, oldIsEagerLoadedConfigurationSource.Value)) { builder = builder.AutoInclude( ((IReadOnlyNavigation)oldNavigation).IsEagerLoaded, oldIsEagerLoadedConfigurationSource.Value)!; } var oldLazyLoadingEnabledConfigurationSource = ((IConventionNavigation)oldNavigation).GetLazyLoadingEnabledConfigurationSource(); if (oldLazyLoadingEnabledConfigurationSource.HasValue && builder.CanSetLazyLoadingEnabled( ((IReadOnlyNavigation)oldNavigation).LazyLoadingEnabled, oldLazyLoadingEnabledConfigurationSource.Value)) { builder = builder.EnableLazyLoading( ((IReadOnlyNavigation)oldNavigation).LazyLoadingEnabled, oldLazyLoadingEnabledConfigurationSource.Value)!; } return builder.Metadata.ForeignKey.Builder; } private InternalForeignKeyBuilder? GetOrCreateRelationshipBuilder( EntityType principalEntityType, EntityType dependentEntityType, MemberIdentity? navigationToPrincipal, MemberIdentity? navigationToDependent, IReadOnlyList<Property>? dependentProperties, IReadOnlyList<Property>? oldNameDependentProperties, IReadOnlyList<Property>? principalProperties, bool? isRequired, bool removeCurrent, ConfigurationSource? principalEndConfigurationSource, ConfigurationSource? configurationSource, out bool? existingRelationshipInverted) { var newRelationshipBuilder = FindCompatibleRelationship( principalEntityType, dependentEntityType, navigationToPrincipal, navigationToDependent, dependentProperties, principalProperties, principalEndConfigurationSource, configurationSource, out existingRelationshipInverted, out var conflictingRelationshipsFound, out var resolvableRelationships); if (conflictingRelationshipsFound) { return null; } // This workaround prevents the properties to be cleaned away before the new FK is created, // this should be replaced with reference counting // Issue #15898 var temporaryProperties = dependentProperties?.Where(p => p.GetConfigurationSource() == ConfigurationSource.Convention && ((IConventionProperty)p).IsImplicitlyCreated()).ToList(); var tempIndex = temporaryProperties?.Count > 0 && dependentEntityType.FindIndex(temporaryProperties) == null ? dependentEntityType.Builder.HasIndex(temporaryProperties, ConfigurationSource.Convention)!.Metadata : null; var temporaryKeyProperties = principalProperties?.Where(p => p.GetConfigurationSource() == ConfigurationSource.Convention && ((IConventionProperty)p).IsImplicitlyCreated()).ToList(); var keyTempIndex = temporaryKeyProperties?.Count > 0 && principalEntityType.FindIndex(temporaryKeyProperties) == null ? principalEntityType.Builder.HasIndex(temporaryKeyProperties, ConfigurationSource.Convention)!.Metadata : null; var removedForeignKeys = new List<ForeignKey>(); var referencingSkipNavigationName = Metadata.ReferencingSkipNavigations?.FirstOrDefault()?.Inverse?.Name; if (!Metadata.IsInModel) { removedForeignKeys.Add(Metadata); } else { if (removeCurrent || newRelationshipBuilder != null) { if (newRelationshipBuilder == this) { newRelationshipBuilder = null; } removedForeignKeys.Add(Metadata); Metadata.DeclaringEntityType.Builder.HasNoRelationship(Metadata, ConfigurationSource.Explicit); } else { existingRelationshipInverted = false; newRelationshipBuilder = Metadata.Builder; } } foreach (var relationshipWithResolution in resolvableRelationships) { var resolvableRelationship = relationshipWithResolution.Builder; var sameConfigurationSource = relationshipWithResolution.SameConfigurationSource; var resolution = relationshipWithResolution.Resolution; var inverseNavigationRemoved = relationshipWithResolution.InverseNavigationShouldBeRemoved; if (sameConfigurationSource && configurationSource == ConfigurationSource.Explicit && inverseNavigationRemoved) { var foreignKey = resolvableRelationship.Metadata; ThrowForConflictingNavigation( foreignKey, principalEntityType, dependentEntityType, navigationToDependent?.Name, navigationToPrincipal?.Name); } if (resolvableRelationship == newRelationshipBuilder) { continue; } if (resolution.HasFlag(Resolution.Remove)) { removedForeignKeys.Add(resolvableRelationship.Metadata); resolvableRelationship.Metadata.DeclaringEntityType.Builder.HasNoRelationship( resolvableRelationship.Metadata, ConfigurationSource.Explicit); continue; } if (resolution.HasFlag(Resolution.ResetToPrincipal)) { resolvableRelationship = resolvableRelationship.HasNavigations( MemberIdentity.None, navigationToDependent: null, resolvableRelationship.Metadata.GetConfigurationSource())!; } if (resolution.HasFlag(Resolution.ResetToDependent)) { resolvableRelationship = resolvableRelationship.HasNavigations( navigationToPrincipal: null, MemberIdentity.None, resolvableRelationship.Metadata.GetConfigurationSource())!; } if (!resolvableRelationship.Metadata.IsInModel) { continue; } var navigationlessForeignKey = resolvableRelationship.Metadata; if (navigationlessForeignKey.DependentToPrincipal == null && navigationlessForeignKey.PrincipalToDependent == null && navigationlessForeignKey.DeclaringEntityType.Builder.HasNoRelationship( navigationlessForeignKey, ConfigurationSource.Convention) != null) { removedForeignKeys.Add(navigationlessForeignKey); } if (resolution.HasFlag(Resolution.ResetDependentProperties)) { var foreignKey = resolvableRelationship.Metadata; resolvableRelationship.HasForeignKey((IReadOnlyList<Property>?)null, foreignKey.GetConfigurationSource()); } } if (newRelationshipBuilder == null) { var principalKey = principalProperties != null ? principalEntityType.GetRootType().Builder.HasKey(principalProperties, configurationSource)!.Metadata : principalEntityType.FindPrimaryKey(); if (principalKey != null) { if (oldNameDependentProperties != null || (dependentProperties != null && !ForeignKey.AreCompatible( principalKey.Properties, dependentProperties, principalEntityType, dependentEntityType, shouldThrow: false) && dependentProperties.All(p => ConfigurationSource.Convention.Overrides(p.GetTypeConfigurationSource()) && (p.IsShadowProperty() || p.IsIndexerProperty())))) { dependentProperties = (oldNameDependentProperties ?? dependentProperties)!; if (principalKey.Properties.Count == dependentProperties.Count) { var detachedProperties = InternalTypeBaseBuilder.DetachProperties(dependentProperties)!; dependentProperties = dependentEntityType.Builder.GetOrCreateProperties( dependentProperties.Select(p => p.Name).ToList(), ConfigurationSource.Convention, principalKey.Properties, isRequired ?? false)!; detachedProperties.Attach(dependentEntityType.Builder); } } if (dependentProperties != null && !ForeignKey.AreCompatible( principalKey.Properties, dependentProperties, principalEntityType, dependentEntityType, shouldThrow: false)) { if (principalProperties == null) { principalKey = null; } else { dependentProperties = null; } } } newRelationshipBuilder = dependentEntityType.Builder.CreateForeignKey( principalEntityType.Builder, dependentProperties, principalKey, navigationToPrincipal?.Name ?? referencingSkipNavigationName, isRequired, ConfigurationSource.Convention)!; } if (tempIndex?.IsInModel == true) { dependentEntityType.RemoveIndex(tempIndex.Properties); } if (keyTempIndex?.IsInModel == true) { keyTempIndex.DeclaringEntityType.RemoveIndex(keyTempIndex.Properties); } if (newRelationshipBuilder == null) { return null; } foreach (var removedForeignKey in removedForeignKeys) { Metadata.DeclaringEntityType.Model.ConventionDispatcher.Tracker.Update(removedForeignKey, newRelationshipBuilder.Metadata); } return newRelationshipBuilder; } private InternalForeignKeyBuilder? FindCompatibleRelationship( EntityType principalEntityType, EntityType dependentEntityType, MemberIdentity? navigationToPrincipal, MemberIdentity? navigationToDependent, IReadOnlyList<Property>? dependentProperties, IReadOnlyList<Property>? principalProperties, ConfigurationSource? principalEndConfigurationSource, ConfigurationSource? configurationSource, out bool? existingRelationshipInverted, out bool conflictingRelationshipsFound, out List<( InternalForeignKeyBuilder Builder, bool SameConfigurationSource, Resolution Resolution, bool InverseNavigationShouldBeRemoved)> resolvableRelationships) { existingRelationshipInverted = null; conflictingRelationshipsFound = false; resolvableRelationships = []; var matchingRelationships = FindRelationships( principalEntityType, dependentEntityType, navigationToPrincipal, navigationToDependent, dependentProperties, principalProperties ?? principalEntityType.FindPrimaryKey()?.Properties) .Where(r => r.Metadata != Metadata) .Distinct(); var unresolvableRelationships = new List<InternalForeignKeyBuilder>(); foreach (var matchingRelationship in matchingRelationships) { var resolvable = true; bool? sameConfigurationSource = null; var inverseNavigationRemoved = false; var resolution = Resolution.None; var navigationToPrincipalName = navigationToPrincipal?.Name; var navigationToDependentName = navigationToDependent?.Name; if (navigationToPrincipalName != null) { if ((navigationToPrincipalName == matchingRelationship.Metadata.DependentToPrincipal?.Name) && (dependentEntityType.IsAssignableFrom(matchingRelationship.Metadata.DeclaringEntityType) || matchingRelationship.Metadata.DeclaringEntityType.IsAssignableFrom(dependentEntityType))) { if (matchingRelationship.CanRemoveNavigation( pointsToPrincipal: true, configurationSource, overrideSameSource: false)) { resolution |= Resolution.ResetToPrincipal; sameConfigurationSource ??= false; } else if (matchingRelationship.CanRemoveNavigation(pointsToPrincipal: true, configurationSource) // Don't remove derived bi-directional navigations && (matchingRelationship.Metadata.GetConfigurationSource() == ConfigurationSource.Explicit || navigationToDependentName != null || matchingRelationship.Metadata.PrincipalToDependent == null || !matchingRelationship.Metadata.DeclaringEntityType.IsStrictlyDerivedFrom(dependentEntityType))) { if (navigationToDependentName != null && matchingRelationship.Metadata.PrincipalToDependent != null && navigationToDependentName != matchingRelationship.Metadata.PrincipalToDependent.Name) { inverseNavigationRemoved = true; } resolution |= Resolution.ResetToPrincipal; sameConfigurationSource = true; } else if (!configurationSource.HasValue || !matchingRelationship.Metadata.DeclaringEntityType.Builder .CanRemoveForeignKey(matchingRelationship.Metadata, configurationSource.Value)) { resolvable = false; } } else if ((navigationToPrincipalName == matchingRelationship.Metadata.PrincipalToDependent?.Name) && (dependentEntityType.IsAssignableFrom(matchingRelationship.Metadata.PrincipalEntityType) || matchingRelationship.Metadata.PrincipalEntityType.IsAssignableFrom(dependentEntityType))) { if (matchingRelationship.CanRemoveNavigation( pointsToPrincipal: false, configurationSource, overrideSameSource: false)) { resolution |= Resolution.ResetToDependent; sameConfigurationSource ??= false; } else if (matchingRelationship.CanRemoveNavigation(pointsToPrincipal: false, configurationSource) // Don't remove derived bi-directional navigations && (matchingRelationship.Metadata.GetConfigurationSource() == ConfigurationSource.Explicit || navigationToDependentName != null || matchingRelationship.Metadata.DependentToPrincipal == null || !matchingRelationship.Metadata.PrincipalEntityType.IsStrictlyDerivedFrom(dependentEntityType))) { if (navigationToDependentName != null && matchingRelationship.Metadata.DependentToPrincipal != null && navigationToDependentName != matchingRelationship.Metadata.DependentToPrincipal.Name) { inverseNavigationRemoved = true; } resolution |= Resolution.ResetToDependent; sameConfigurationSource = true; } else if (!configurationSource.HasValue || !matchingRelationship.Metadata.DeclaringEntityType.Builder .CanRemoveForeignKey(matchingRelationship.Metadata, configurationSource.Value)) { resolvable = false; } } } if (navigationToDependentName != null) { if ((navigationToDependentName == matchingRelationship.Metadata.PrincipalToDependent?.Name) && (principalEntityType.IsAssignableFrom(matchingRelationship.Metadata.PrincipalEntityType) || matchingRelationship.Metadata.PrincipalEntityType.IsAssignableFrom(principalEntityType))) { if (matchingRelationship.CanRemoveNavigation( pointsToPrincipal: false, configurationSource, overrideSameSource: false)) { resolution |= Resolution.ResetToDependent; sameConfigurationSource ??= false; } else if (matchingRelationship.CanRemoveNavigation(pointsToPrincipal: false, configurationSource) // Don't remove derived bi-directional navigations && (matchingRelationship.Metadata.GetConfigurationSource() == ConfigurationSource.Explicit || navigationToPrincipalName != null || matchingRelationship.Metadata.DependentToPrincipal == null || !matchingRelationship.Metadata.PrincipalEntityType.IsStrictlyDerivedFrom(principalEntityType))) { if (navigationToPrincipalName != null && matchingRelationship.Metadata.DependentToPrincipal != null && navigationToPrincipalName != matchingRelationship.Metadata.DependentToPrincipal.Name) { inverseNavigationRemoved = true; } resolution |= Resolution.ResetToDependent; sameConfigurationSource = true; } else if (!configurationSource.HasValue || !matchingRelationship.Metadata.DeclaringEntityType.Builder .CanRemoveForeignKey(matchingRelationship.Metadata, configurationSource.Value)) { resolvable = false; } } else if ((navigationToDependentName == matchingRelationship.Metadata.DependentToPrincipal?.Name) && (principalEntityType.IsAssignableFrom(matchingRelationship.Metadata.DeclaringEntityType) || matchingRelationship.Metadata.DeclaringEntityType.IsAssignableFrom(principalEntityType))) { if (matchingRelationship.CanRemoveNavigation( pointsToPrincipal: true, configurationSource, overrideSameSource: false)) { resolution |= Resolution.ResetToPrincipal; sameConfigurationSource ??= false; } else if (matchingRelationship.CanRemoveNavigation(pointsToPrincipal: true, configurationSource) // Don't remove derived bi-directional navigations && (matchingRelationship.Metadata.GetConfigurationSource() == ConfigurationSource.Explicit || navigationToPrincipalName != null || matchingRelationship.Metadata.PrincipalToDependent == null || !matchingRelationship.Metadata.DeclaringEntityType.IsStrictlyDerivedFrom(principalEntityType))) { if (navigationToPrincipalName != null && matchingRelationship.Metadata.PrincipalToDependent != null && navigationToPrincipalName != matchingRelationship.Metadata.PrincipalToDependent.Name) { inverseNavigationRemoved = true; } resolution |= Resolution.ResetToPrincipal; sameConfigurationSource = true; } else if (!configurationSource.HasValue || !matchingRelationship.Metadata.DeclaringEntityType.Builder .CanRemoveForeignKey(matchingRelationship.Metadata, configurationSource.Value)) { resolvable = false; } } } if (dependentProperties != null && matchingRelationship.Metadata.Properties.SequenceEqual(dependentProperties)) { if (matchingRelationship.CanSetForeignKey( properties: null, dependentEntityType: null, configurationSource, overrideSameSource: false)) { resolution |= Resolution.ResetDependentProperties; sameConfigurationSource ??= false; } else if (matchingRelationship.CanSetForeignKey(properties: null, configurationSource)) { resolution |= Resolution.ResetDependentProperties; sameConfigurationSource = true; } else { resolvable = false; } } if (resolvable) { if ((sameConfigurationSource ?? true) && configurationSource.HasValue && matchingRelationship.Metadata.DeclaringEntityType.Builder .CanRemoveForeignKey(matchingRelationship.Metadata, configurationSource.Value)) { resolution |= Resolution.Remove; } resolvableRelationships.Add( (matchingRelationship, sameConfigurationSource ?? true, resolution, inverseNavigationRemoved)); } else { unresolvableRelationships.Add(matchingRelationship); } } InternalForeignKeyBuilder? newRelationshipBuilder = null; var candidates = unresolvableRelationships.Concat( resolvableRelationships.Where(r => r.SameConfigurationSource).Concat( resolvableRelationships.Where(r => !r.SameConfigurationSource)) .Select(r => r.Builder)); foreach (var candidateRelationship in candidates) { var candidateFk = candidateRelationship.Metadata; if (principalEndConfigurationSource.OverridesStrictly( candidateFk.GetDependentToPrincipalConfigurationSource()) && (principalEntityType != candidateFk.PrincipalEntityType || dependentEntityType != candidateFk.DeclaringEntityType) && (principalEntityType.IsAssignableFrom(dependentEntityType) || dependentEntityType.IsAssignableFrom(principalEntityType))) { // Favor the intra-hierarchical relationship with higher configuration source continue; } if (!candidateRelationship.CanSetRelatedTypes( principalEntityType, dependentEntityType, strictPrincipal: principalEndConfigurationSource.HasValue && principalEndConfigurationSource.Overrides(Metadata.GetPrincipalEndConfigurationSource()), navigationToPrincipal, navigationToDependent, configurationSource, shouldThrow: false, out var candidateRelationshipInverted, out var shouldResetToPrincipal, out var shouldResetToDependent, out _, out _, out _)) { continue; } if (configurationSource != ConfigurationSource.Explicit && (shouldResetToPrincipal || shouldResetToDependent) && (navigationToPrincipal?.Name is null || navigationToDependent?.Name is null) && candidateFk is { DependentToPrincipal: not null, PrincipalToDependent: not null } && ((!candidateRelationshipInverted && principalEntityType.IsAssignableFrom(candidateFk.PrincipalEntityType) && dependentEntityType.IsAssignableFrom(candidateFk.DeclaringEntityType)) || (candidateRelationshipInverted && principalEntityType.IsAssignableFrom(candidateFk.DeclaringEntityType) && dependentEntityType.IsAssignableFrom(candidateFk.PrincipalEntityType)))) { // Favor derived bi-directional relationships over one-directional on base continue; } if (dependentProperties != null && !Property.AreCompatible(dependentProperties, candidateFk.DeclaringEntityType)) { continue; } if (principalProperties != null && !Property.AreCompatible(principalProperties, candidateFk.PrincipalEntityType)) { continue; } existingRelationshipInverted = candidateRelationshipInverted; newRelationshipBuilder ??= candidateRelationship; break; } if (unresolvableRelationships.Any(r => r != newRelationshipBuilder)) { conflictingRelationshipsFound = true; return null; } return newRelationshipBuilder; } /// <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> public static void ThrowForConflictingNavigation( IReadOnlyForeignKey foreignKey, string newInverseName, bool newToPrincipal) => ThrowForConflictingNavigation( foreignKey, foreignKey.PrincipalEntityType, foreignKey.DeclaringEntityType, newToPrincipal ? foreignKey.PrincipalToDependent?.Name : newInverseName, newToPrincipal ? newInverseName : foreignKey.DependentToPrincipal?.Name); /// <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> public static void ThrowForConflictingNavigation( IReadOnlyForeignKey foreignKey, IReadOnlyEntityType principalEntityType, IReadOnlyEntityType dependentEntityType, string? navigationToDependent, string? navigationToPrincipal) => throw new InvalidOperationException( CoreStrings.ConflictingRelationshipNavigation( principalEntityType.DisplayName() + (navigationToDependent == null ? "" : "." + navigationToDependent), dependentEntityType.DisplayName() + (navigationToPrincipal == null ? "" : "." + navigationToPrincipal), foreignKey.PrincipalEntityType.DisplayName() + (foreignKey.PrincipalToDependent == null ? "" : "." + foreignKey.PrincipalToDependent.Name), foreignKey.DeclaringEntityType.DisplayName() + (foreignKey.DependentToPrincipal == null ? "" : "." + foreignKey.DependentToPrincipal.Name))); private static IReadOnlyList<InternalForeignKeyBuilder> FindRelationships( EntityType principalEntityType, EntityType dependentEntityType, MemberIdentity? navigationToPrincipal, MemberIdentity? navigationToDependent, IReadOnlyList<Property>? dependentProperties, IReadOnlyList<Property>? principalProperties) { var existingRelationships = new List<InternalForeignKeyBuilder>(); if (navigationToPrincipal?.Name != null) { existingRelationships.AddRange( dependentEntityType .FindNavigationsInHierarchy(navigationToPrincipal.Value.Name) .Select(n => n.ForeignKey.Builder)); } if (navigationToDependent?.Name != null) { existingRelationships.AddRange( principalEntityType .FindNavigationsInHierarchy(navigationToDependent.Value.Name) .Select(n => n.ForeignKey.Builder)); } if (dependentProperties != null) { if (principalProperties != null) { var principalKey = principalEntityType.FindKey(principalProperties); if (principalKey != null) { existingRelationships.AddRange( dependentEntityType .FindForeignKeysInHierarchy(dependentProperties, principalKey, principalEntityType) .Select(fk => fk.Builder)); } } else { existingRelationships.AddRange( dependentEntityType .FindForeignKeysInHierarchy(dependentProperties) .Where(fk => fk.PrincipalEntityType == principalEntityType) .Select(fk => fk.Builder)); } } return existingRelationships; } /// <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> public static InternalForeignKeyBuilder? FindCurrentForeignKeyBuilder( EntityType principalEntityType, EntityType dependentEntityType, MemberIdentity? navigationToPrincipal, MemberIdentity? navigationToDependent, IReadOnlyList<Property>? dependentProperties, IReadOnlyList<Property>? principalProperties) { InternalForeignKeyBuilder? currentRelationship = null; var matchingRelationships = FindRelationships( principalEntityType, dependentEntityType, navigationToPrincipal, navigationToDependent, dependentProperties, principalProperties).Distinct(); foreach (var matchingRelationship in matchingRelationships) { if (!matchingRelationship.Metadata.DeclaringEntityType.IsAssignableFrom(dependentEntityType)) { continue; } if (!matchingRelationship.Metadata.PrincipalEntityType.IsAssignableFrom(principalEntityType)) { continue; } var matchingForeignKey = matchingRelationship.Metadata; var sameHierarchyInvertedNavigations = (principalEntityType.IsAssignableFrom(dependentEntityType) || dependentEntityType.IsAssignableFrom(principalEntityType)) && (navigationToPrincipal == null || navigationToPrincipal.Value.Name == matchingForeignKey.PrincipalToDependent?.Name) && (navigationToDependent == null || navigationToDependent.Value.Name == matchingForeignKey.DependentToPrincipal?.Name); if (!sameHierarchyInvertedNavigations) { if (navigationToPrincipal != null && matchingForeignKey.DependentToPrincipal?.Name != navigationToPrincipal.Value.Name) { continue; } if (navigationToDependent != null && matchingForeignKey.PrincipalToDependent?.Name != navigationToDependent.Value.Name) { continue; } } if (dependentProperties != null && !matchingForeignKey.Properties.SequenceEqual(dependentProperties)) { continue; } if (principalProperties != null && !matchingForeignKey.PrincipalKey.Properties.SequenceEqual(principalProperties)) { continue; } if (currentRelationship != null) { // More than one match, ambiguity should be dealt with later return null; } currentRelationship = matchingRelationship; } return currentRelationship; } /// <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> public virtual InternalForeignKeyBuilder? Attach(InternalEntityTypeBuilder entityTypeBuilder) { var configurationSource = Metadata.GetConfigurationSource(); var model = Metadata.DeclaringEntityType.Model; InternalEntityTypeBuilder principalEntityTypeBuilder; EntityType? principalEntityType; if (Metadata.PrincipalEntityType.IsInModel) { principalEntityTypeBuilder = Metadata.PrincipalEntityType.Builder; principalEntityType = Metadata.PrincipalEntityType; } else { if (Metadata.PrincipalEntityType.Name == entityTypeBuilder.Metadata.Name || Metadata.PrincipalEntityType.ClrType == entityTypeBuilder.Metadata.ClrType) { principalEntityTypeBuilder = entityTypeBuilder; principalEntityType = entityTypeBuilder.Metadata; } else { principalEntityType = model.FindEntityType(Metadata.PrincipalEntityType.Name); if (principalEntityType == null) { var ownership = Metadata.PrincipalEntityType.FindOwnership(); if (Metadata.PrincipalEntityType.HasSharedClrType && ownership is { PrincipalEntityType.IsInModel: true }) { principalEntityType = model.FindEntityType( Metadata.PrincipalEntityType.ClrType, ownership.PrincipalToDependent!.Name, ownership.PrincipalEntityType); if (principalEntityType == null) { return null; } } else { return null; } } principalEntityTypeBuilder = principalEntityType.Builder; } } InternalEntityTypeBuilder dependentEntityTypeBuilder; EntityType? dependentEntityType; if (Metadata.DeclaringEntityType.IsInModel) { dependentEntityTypeBuilder = Metadata.DeclaringEntityType.Builder; dependentEntityType = Metadata.DeclaringEntityType; } else { if ((Metadata.DeclaringEntityType.Name == entityTypeBuilder.Metadata.Name || Metadata.DeclaringEntityType.ClrType == entityTypeBuilder.Metadata.ClrType) && (!principalEntityType.HasSharedClrType || principalEntityType != entityTypeBuilder.Metadata)) { dependentEntityTypeBuilder = entityTypeBuilder; dependentEntityType = entityTypeBuilder.Metadata; } else { dependentEntityType = model.FindEntityType(Metadata.DeclaringEntityType.Name); if (dependentEntityType == null) { using (ModelBuilder.Metadata.DelayConventions()) { if (Metadata.DeclaringEntityType.HasSharedClrType || model.IsShared(Metadata.DeclaringEntityType.ClrType)) { if (Metadata is { IsOwnership: true, PrincipalToDependent: not null }) { var name = principalEntityType.GetOwnedName( Metadata.DeclaringEntityType.ShortName(), Metadata.PrincipalToDependent.Name); dependentEntityType = ModelBuilder.SharedTypeEntity( name, Metadata.DeclaringEntityType.ClrType, Metadata.DeclaringEntityType.GetConfigurationSource(), shouldBeOwned: true)!.Metadata; } else { return null; } } else { dependentEntityType = ModelBuilder.Entity( Metadata.DeclaringEntityType.ClrType, configurationSource, shouldBeOwned: Metadata.DeclaringEntityType.IsOwned()) !.Metadata; } } } dependentEntityTypeBuilder = dependentEntityType.Builder; } } if (!Metadata.IsOwnership && !Metadata.GetConfigurationSource().Overrides(ConfigurationSource.Explicit)) { if (principalEntityType.IsOwned() && Metadata.DependentToPrincipal != null && !dependentEntityType.IsInOwnershipPath(principalEntityType)) { // An entity type can have a navigation to a principal owned type only if it's in the ownership path return null; } if (dependentEntityType.IsOwned() && Metadata.PrincipalToDependent != null && (dependentEntityType.FindOwnership()?.PrincipalEntityType == principalEntityType || !dependentEntityType.IsInOwnershipPath(principalEntityType))) { // Only a type in the ownership path can have a navigation to an owned dependent return null; } } if (dependentEntityType.GetForeignKeys().Contains(Metadata, ReferenceEqualityComparer.Instance)) { Check.DebugAssert(Metadata.IsInModel, "Metadata isn't in the model"); return Metadata.Builder; } IReadOnlyList<Property> dependentProperties; IReadOnlyList<Property> principalProperties; if (Metadata.GetPrincipalKeyConfigurationSource()?.Overrides(configurationSource) != true) { principalProperties = new List<Property>(); } else { principalProperties = principalEntityTypeBuilder.GetActualProperties(Metadata.PrincipalKey.Properties, configurationSource) ?? new List<Property>(); } if ((principalProperties.Count == 0 && Metadata.GetPropertiesConfigurationSource()?.Overrides(ConfigurationSource.Explicit) != true) || Metadata.GetPropertiesConfigurationSource()?.Overrides(configurationSource) != true) { dependentProperties = new List<Property>(); } else { dependentProperties = dependentEntityTypeBuilder.GetActualProperties(Metadata.Properties, configurationSource) ?? new List<Property>(); } if (dependentProperties.Count != 0) { if (!CanSetForeignKey( dependentProperties, dependentEntityType, principalProperties.Count != 0 ? principalProperties : Metadata.PrincipalKey.Properties, principalEntityType, configurationSource, out var resetPrincipalKey)) { dependentProperties = new List<Property>(); } else if (resetPrincipalKey) { principalProperties = new List<Property>(); } } return ReplaceForeignKey( configurationSource, principalEntityTypeBuilder, dependentEntityTypeBuilder, dependentProperties: dependentProperties, principalProperties: principalProperties); } /// <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> public static bool AreCompatible( EntityType principalEntityType, EntityType dependentEntityType, MemberInfo? navigationToPrincipal, MemberInfo? navigationToDependent, IReadOnlyList<Property>? dependentProperties, IReadOnlyList<Property>? principalProperties, bool? isUnique, ConfigurationSource? configurationSource) => ForeignKey.AreCompatible( principalEntityType, dependentEntityType, navigationToPrincipal, navigationToDependent, dependentProperties, principalProperties, isUnique, configurationSource == ConfigurationSource.Explicit); private bool CanSetRelatedTypes( EntityType principalEntityType, EntityType dependentEntityType, bool strictPrincipal, MemberIdentity? navigationToPrincipal, MemberIdentity? navigationToDependent, ConfigurationSource? configurationSource, bool shouldThrow, out bool shouldInvert, out bool shouldResetToPrincipal, out bool shouldResetToDependent, out bool shouldResetPrincipalProperties, out bool shouldResetDependentProperties, out bool? shouldBeUnique) { shouldInvert = false; shouldResetToPrincipal = false; shouldResetToDependent = false; shouldResetPrincipalProperties = false; shouldResetDependentProperties = false; shouldBeUnique = null; var sameHierarchyInvertedNavigations = (principalEntityType.IsAssignableFrom(dependentEntityType) || dependentEntityType.IsAssignableFrom(principalEntityType)) && (((navigationToPrincipal != null) && (navigationToPrincipal.Value.Name == Metadata.PrincipalToDependent?.Name)) || ((navigationToDependent != null) && (navigationToDependent.Value.Name == Metadata.DependentToPrincipal?.Name)) || ((navigationToPrincipal == null) && (navigationToDependent == null) && principalEntityType == Metadata.DeclaringEntityType && dependentEntityType == Metadata.PrincipalEntityType)); var someAspectsFitNonInverted = false; if (!sameHierarchyInvertedNavigations && CanSetRelatedTypes( principalEntityType, dependentEntityType, navigationToPrincipal, navigationToDependent, configurationSource, inverted: false, shouldThrow: false, out shouldResetToPrincipal, out shouldResetToDependent, out shouldResetPrincipalProperties, out shouldResetDependentProperties, out shouldBeUnique)) { if (!shouldResetToPrincipal && !shouldResetToDependent) { return true; } someAspectsFitNonInverted = true; } var canInvert = configurationSource?.Overrides(Metadata.GetPrincipalEndConfigurationSource()) == true; if ((!strictPrincipal || canInvert) && CanSetRelatedTypes( dependentEntityType, principalEntityType, navigationToDependent, navigationToPrincipal, configurationSource, strictPrincipal, shouldThrow: false, out var invertedShouldResetToPrincipal, out var invertedShouldResetToDependent, out _, out _, out var invertedShouldBeUnique) && (!someAspectsFitNonInverted || (!invertedShouldResetToPrincipal && !invertedShouldResetToDependent))) { shouldInvert = true; shouldResetToPrincipal = invertedShouldResetToDependent; shouldResetToDependent = invertedShouldResetToPrincipal; shouldBeUnique = invertedShouldBeUnique; return true; } if (!someAspectsFitNonInverted && shouldThrow) { if (strictPrincipal && principalEntityType.IsKeyless) { throw new InvalidOperationException( CoreStrings.PrincipalKeylessType( principalEntityType.DisplayName(), Metadata.PrincipalEntityType.DisplayName() + (Metadata.PrincipalToDependent == null ? "" : "." + Metadata.PrincipalToDependent.Name), Metadata.DeclaringEntityType.DisplayName() + (Metadata.DependentToPrincipal == null ? "" : "." + Metadata.DependentToPrincipal.Name))); } if (canInvert) { throw new InvalidOperationException( CoreStrings.EntityTypesNotInRelationship( dependentEntityType.DisplayName(), principalEntityType.DisplayName(), Metadata.DeclaringEntityType.DisplayName(), Metadata.PrincipalEntityType.DisplayName())); } } return someAspectsFitNonInverted; } private bool CanSetRelatedTypes( EntityType principalEntityType, EntityType dependentEntityType, MemberIdentity? navigationToPrincipal, MemberIdentity? navigationToDependent, ConfigurationSource? configurationSource, bool inverted, bool shouldThrow, out bool shouldResetToPrincipal, out bool shouldResetToDependent, out bool shouldResetPrincipalProperties, out bool shouldResetDependentProperties, out bool? shouldBeUnique) { shouldResetToPrincipal = false; shouldResetToDependent = false; shouldResetPrincipalProperties = false; shouldResetDependentProperties = false; shouldBeUnique = null; if (!Metadata.DeclaringEntityType.IsAssignableFrom(dependentEntityType) && !dependentEntityType.IsAssignableFrom(Metadata.DeclaringEntityType)) { return false; } if (!Metadata.PrincipalEntityType.IsAssignableFrom(principalEntityType) && !principalEntityType.IsAssignableFrom(Metadata.PrincipalEntityType)) { return false; } if (inverted) { if (dependentEntityType.IsKeyless && !configurationSource.OverridesStrictly(dependentEntityType.GetIsKeylessConfigurationSource())) { return false; } } else { if (principalEntityType.IsKeyless && !configurationSource.OverridesStrictly(principalEntityType.GetIsKeylessConfigurationSource())) { return false; } } if (navigationToPrincipal != null) { if (!configurationSource.HasValue || !CanSetNavigation( navigationToPrincipal.Value, pointsToPrincipal: true, configurationSource.Value, shouldThrow, shouldBeUnique: out _)) { return false; } if (Metadata.DependentToPrincipal != null && navigationToPrincipal.Value.Name != Metadata.DependentToPrincipal.Name) { shouldResetToPrincipal = true; } } else { bool? invertedShouldBeUnique = null; var navigationToPrincipalProperty = Metadata.DependentToPrincipal?.GetIdentifyingMemberInfo(); if (navigationToPrincipalProperty != null && !IsCompatible( navigationToPrincipalProperty, !inverted, inverted ? principalEntityType : dependentEntityType, inverted ? dependentEntityType : principalEntityType, shouldThrow, out invertedShouldBeUnique)) { if (!configurationSource.HasValue || !CanSetNavigation((string?)null, pointsToPrincipal: true, configurationSource.Value)) { return false; } shouldResetToPrincipal = true; } if (inverted) { shouldBeUnique = invertedShouldBeUnique; } } if (navigationToDependent != null) { if (!configurationSource.HasValue || !CanSetNavigation( navigationToDependent.Value, pointsToPrincipal: false, configurationSource.Value, shouldThrow, out var toDependentShouldBeUnique)) { return false; } if (Metadata.PrincipalToDependent != null && navigationToDependent.Value.Name != Metadata.PrincipalToDependent.Name) { shouldResetToDependent = true; } if (toDependentShouldBeUnique != null) { shouldBeUnique = toDependentShouldBeUnique; } } else { bool? toDependentShouldBeUnique = null; var navigationToDependentProperty = Metadata.PrincipalToDependent?.GetIdentifyingMemberInfo(); if (navigationToDependentProperty != null && !IsCompatible( navigationToDependentProperty, inverted, inverted ? principalEntityType : dependentEntityType, inverted ? dependentEntityType : principalEntityType, shouldThrow, out toDependentShouldBeUnique)) { if (!configurationSource.HasValue || !CanSetNavigation((string?)null, pointsToPrincipal: false, configurationSource.Value)) { return false; } shouldResetToDependent = true; } if (!inverted && toDependentShouldBeUnique != null) { shouldBeUnique = toDependentShouldBeUnique; } } if (shouldBeUnique.HasValue && !CanSetIsUnique(shouldBeUnique.Value, configurationSource, out _)) { return false; } if (!Property.AreCompatible(Metadata.PrincipalKey.Properties, principalEntityType)) { if (!configurationSource.HasValue || !configurationSource.Value.Overrides(Metadata.GetPrincipalKeyConfigurationSource())) { return false; } shouldResetPrincipalProperties = true; } if (!Property.AreCompatible(Metadata.Properties, dependentEntityType)) { if (!configurationSource.HasValue || !configurationSource.Value.Overrides(Metadata.GetPropertiesConfigurationSource())) { return false; } shouldResetDependentProperties = true; } return true; } [Flags]
InternalForeignKeyBuilder
csharp
moq__moq4
src/Moq.Tests/Regressions/IssueReportsFixture.cs
{ "start": 50166, "end": 50211 }
public class ____ : Fruit { }
Orange
csharp
dotnet__aspnetcore
src/Mvc/test/Mvc.FunctionalTests/ControllerFromServicesTests.cs
{ "start": 2386, "end": 2875 }
record ____"; // Act var response = await Client.PutAsync( "http://localhost/employee/update_records?recordId=employee303", new StringContent(string.Empty)); // Assert response.EnsureSuccessStatusCode(); Assert.Equal(expected, await response.Content.ReadAsStringAsync()); } [Fact] public async Task TypesWithControllerSuffixAreConventionalRouted() { // Arrange var expected = "Saved
employee303
csharp
GtkSharp__GtkSharp
Source/Libs/GLibSharp/GLibSharp.SourceFuncNative.cs
{ "start": 1130, "end": 2116 }
internal class ____ { public bool NativeCallback (IntPtr user_data) { try { bool __ret = managed (user_data); if (release_on_call) gch.Free (); return __ret; } catch (Exception e) { GLib.ExceptionManager.RaiseUnhandledException (e, false); return false; } } bool release_on_call = false; GCHandle gch; public void PersistUntilCalled () { release_on_call = true; gch = GCHandle.Alloc (this); } internal SourceFuncNative NativeDelegate; GLib.SourceFunc managed; public SourceFuncWrapper (GLib.SourceFunc managed) { this.managed = managed; if (managed != null) NativeDelegate = new SourceFuncNative (NativeCallback); } public static GLib.SourceFunc GetManagedDelegate (SourceFuncNative native) { if (native == null) return null; SourceFuncWrapper wrapper = (SourceFuncWrapper) native.Target; if (wrapper == null) return null; return wrapper.managed; } } #endregion }
SourceFuncWrapper
csharp
MassTransit__MassTransit
tests/MassTransit.ActiveMqTransport.Tests/Reconnecting_Specs.cs
{ "start": 335, "end": 2494 }
public class ____ : ActiveMqTestFixture { public Reconnecting_Specs(string protocol) : base(protocol) { } [Test] [Explicit] public async Task Should_fault_nicely() { await Bus.Publish(new ReconnectMessage { Value = "Before" }); var beforeFound = await Task.Run(() => _consumer.Received.Select<ReconnectMessage>(x => x.Context.Message.Value == "Before").Any()); Assert.That(beforeFound, Is.True); Console.WriteLine("Okay, restart ActiveMQ"); for (var i = 0; i < 20; i++) { await Task.Delay(1000); Console.Write($"{i}. "); var clientFactory = Bus.CreateClientFactory(TestTimeout); RequestHandle<PingMessage> request = clientFactory.CreateRequest(new PingMessage()); Response<PongMessage> response = await request.GetResponse<PongMessage>(); if (clientFactory is IAsyncDisposable asyncDisposable) await asyncDisposable.DisposeAsync(); } Console.WriteLine(""); Console.WriteLine("Resuming"); await Bus.Publish(new ReconnectMessage { Value = "After" }); var afterFound = await Task.Run(() => _consumer.Received.Select<ReconnectMessage>(x => x.Context.Message.Value == "After").Any()); Assert.That(afterFound, Is.True); } public Reconnecting_Specs() { SendEndpointCacheDefaults.MinAge = TimeSpan.FromSeconds(2); SendEndpointCacheDefaults.Capacity = 5; } ReconnectConsumer _consumer; protected override void ConfigureActiveMqReceiveEndpoint(IActiveMqReceiveEndpointConfigurator configurator) { base.ConfigureActiveMqReceiveEndpoint(configurator); _consumer = new ReconnectConsumer(TestTimeout); _consumer.Configure(configurator); configurator.Handler<PingMessage>(context => context.RespondAsync(new PongMessage(context.Message.CorrelationId))); }
Reconnecting_Specs
csharp
grandnode__grandnode2
src/Web/Grand.Web.Common/Extensions/ModelStateExtensions.cs
{ "start": 87, "end": 963 }
public static class ____ { public static object SerializeErrors(this ModelStateDictionary modelStateDictionary) { return modelStateDictionary.Where(entry => entry.Value != null && entry.Value.Errors.Any()) .ToDictionary(entry => entry.Key, entry => SerializeModelState(entry.Value)); } private static Dictionary<string, object> SerializeModelState(ModelStateEntry modelState) { var dictionary = new Dictionary<string, object> { ["errors"] = modelState.Errors.Select(modelError => modelError.ErrorMessage) .Where(errorText => !string.IsNullOrEmpty(errorText)).ToArray() }; return dictionary; } public static object ToDataSourceResult(this ModelStateDictionary modelState) { return !modelState.IsValid ? modelState.SerializeErrors() : null; } }
ModelStateExtensions
csharp
AutoMapper__AutoMapper
src/Benchmark/FlatteningMapper.cs
{ "start": 14253, "end": 14338 }
public class ____ { public string IAmACoolProperty { get; set; } }
ModelSubSubObject
csharp
grpc__grpc-dotnet
src/Shared/Http3ErrorCode.cs
{ "start": 669, "end": 1257 }
internal enum ____ : long { H3_NO_ERROR = 0x100, H3_GENERAL_PROTOCOL_ERROR = 0x101, H3_INTERNAL_ERROR = 0x102, H3_STREAM_CREATION_ERROR = 0x103, H3_CLOSED_CRITICAL_STREAM = 0x104, H3_FRAME_UNEXPECTED = 0x105, H3_FRAME_ERROR = 0x106, H3_EXCESSIVE_LOAD = 0x107, H3_ID_ERROR = 0x108, H3_SETTINGS_ERROR = 0x109, H3_MISSING_SETTINGS = 0x10a, H3_REQUEST_REJECTED = 0x10b, H3_REQUEST_CANCELLED = 0x10c, H3_REQUEST_INCOMPLETE = 0x10d, H3_MESSAGE_ERROR = 0x10e, H3_CONNECT_ERROR = 0x10f, H3_VERSION_FALLBACK = 0x110, }
Http3ErrorCode
csharp
ChilliCream__graphql-platform
src/HotChocolate/Diagnostics/src/Diagnostics/ActivityEnricher.cs
{ "start": 731, "end": 828 }
class ____ override the enricher methods to provide more or /// less information. /// </summary>
and
csharp
ServiceStack__ServiceStack
ServiceStack/tests/ServiceStack.Common.Tests/NativeTypesTests.cs
{ "start": 14441, "end": 14505 }
public class ____ { } [Route("/Request1/", "GET")]
EmbeddedRequest
csharp
dotnet__efcore
src/Microsoft.Data.Sqlite.Core/Extensions/SqliteConnectionExtensions.cs
{ "start": 214, "end": 1203 }
internal static class ____ { public static int ExecuteNonQuery( this SqliteConnection connection, string commandText, params SqliteParameter[] parameters) { using var command = connection.CreateCommand(); command.CommandText = commandText; command.Parameters.AddRange(parameters); return command.ExecuteNonQuery(); } public static T ExecuteScalar<T>( this SqliteConnection connection, string commandText, params SqliteParameter[] parameters) => (T)connection.ExecuteScalar(commandText, parameters)!; private static object? ExecuteScalar( this SqliteConnection connection, string commandText, params SqliteParameter[] parameters) { using var command = connection.CreateCommand(); command.CommandText = commandText; command.Parameters.AddRange(parameters); return command.ExecuteScalar(); } }
SqliteConnectionExtensions
csharp
fluentassertions__fluentassertions
Tests/FluentAssertions.Specs/Primitives/StringAssertionSpecs.cs
{ "start": 705, "end": 996 }
private sealed class ____ : IEqualityComparer<string> { public bool Equals(string x, string y) { return true; } public int GetHashCode(string obj) { return obj.GetHashCode(); } }
AlwaysMatchingEqualityComparer
csharp
CommunityToolkit__dotnet
tests/CommunityToolkit.Mvvm.SourceGenerators.UnitTests/Test_SourceGeneratorsDiagnostics.cs
{ "start": 25887, "end": 26581 }
public partial class ____ : ObservableObject { [ObservableProperty] [NotifyCanExecuteChangedFor(nameof(Foo))] private string name; public void Foo() { } } } """; VerifyGeneratedDiagnostics<ObservablePropertyGenerator>(source, "MVVMTK0016"); } [TestMethod] public void NotifyCanExecuteChangedForInvalidTargetError_InvalidPropertyType() { string source = """ using CommunityToolkit.Mvvm.ComponentModel; namespace MyApp {
SampleViewModel
csharp
icsharpcode__AvalonEdit
ICSharpCode.AvalonEdit/Editing/TextAreaDefaultInputHandlers.cs
{ "start": 1383, "end": 4557 }
public class ____ : TextAreaInputHandler { /// <summary> /// Gets the caret navigation input handler. /// </summary> public TextAreaInputHandler CaretNavigation { get; private set; } /// <summary> /// Gets the editing input handler. /// </summary> public TextAreaInputHandler Editing { get; private set; } /// <summary> /// Gets the mouse selection input handler. /// </summary> public ITextAreaInputHandler MouseSelection { get; private set; } /// <summary> /// Creates a new TextAreaDefaultInputHandler instance. /// </summary> public TextAreaDefaultInputHandler(TextArea textArea) : base(textArea) { this.NestedInputHandlers.Add(CaretNavigation = CaretNavigationCommandHandler.Create(textArea)); this.NestedInputHandlers.Add(Editing = EditingCommandHandler.Create(textArea)); this.NestedInputHandlers.Add(MouseSelection = new SelectionMouseHandler(textArea)); this.CommandBindings.Add(new CommandBinding(ApplicationCommands.Undo, ExecuteUndo, CanExecuteUndo)); this.CommandBindings.Add(new CommandBinding(ApplicationCommands.Redo, ExecuteRedo, CanExecuteRedo)); } internal static KeyBinding CreateFrozenKeyBinding(ICommand command, ModifierKeys modifiers, Key key) { KeyBinding kb = new KeyBinding(command, key, modifiers); // Mark KeyBindings as frozen because they're shared between multiple editor instances. // KeyBinding derives from Freezable only in .NET 4, so we have to use this little trick: Freezable f = ((object)kb) as Freezable; if (f != null) f.Freeze(); return kb; } internal static void WorkaroundWPFMemoryLeak(List<InputBinding> inputBindings) { // Work around WPF memory leak: // KeyBinding retains a reference to whichever UIElement it is used in first. // Using a dummy element for this purpose ensures that we don't leak // a real text editor (with a potentially large document). UIElement dummyElement = new UIElement(); dummyElement.InputBindings.AddRange(inputBindings); } #region Undo / Redo UndoStack GetUndoStack() { TextDocument document = this.TextArea.Document; if (document != null) return document.UndoStack; else return null; } void ExecuteUndo(object sender, ExecutedRoutedEventArgs e) { var undoStack = GetUndoStack(); if (undoStack != null) { if (undoStack.CanUndo) { undoStack.Undo(); this.TextArea.Caret.BringCaretToView(); } e.Handled = true; } } void CanExecuteUndo(object sender, CanExecuteRoutedEventArgs e) { var undoStack = GetUndoStack(); if (undoStack != null) { e.Handled = true; e.CanExecute = undoStack.CanUndo; } } void ExecuteRedo(object sender, ExecutedRoutedEventArgs e) { var undoStack = GetUndoStack(); if (undoStack != null) { if (undoStack.CanRedo) { undoStack.Redo(); this.TextArea.Caret.BringCaretToView(); } e.Handled = true; } } void CanExecuteRedo(object sender, CanExecuteRoutedEventArgs e) { var undoStack = GetUndoStack(); if (undoStack != null) { e.Handled = true; e.CanExecute = undoStack.CanRedo; } } #endregion } }
TextAreaDefaultInputHandler
csharp
files-community__Files
src/Files.App/Data/Items/WidgetRecentItem.cs
{ "start": 307, "end": 1824 }
partial class ____ : WidgetCardItem, IEquatable<RecentItem>, IDisposable { private BitmapImage? _Icon; /// <summary> /// Gets or sets thumbnail icon of the recent item. /// </summary> public BitmapImage? Icon { get => _Icon; set => SetProperty(ref _Icon, value); } /// <summary> /// Gets or sets name of the recent item. /// </summary> public required string Name { get; set; } /// <summary> /// Gets or sets target path of the recent item. /// </summary> public required DateTime LastModified { get; set; } /// <summary> /// Gets or initializes PIDL of the recent item. /// </summary> /// <remarks> /// This has to be removed in the future. /// </remarks> public unsafe required ComPtr<IShellItem> ShellItem { get; init; } /// <summary> /// Loads thumbnail icon of the recent item. /// </summary> /// <returns></returns> public async Task LoadRecentItemIconAsync() { var result = await FileThumbnailHelper.GetIconAsync(Path, Constants.ShellIconSizes.Small, false, IconOptions.UseCurrentScale); var bitmapImage = await result.ToBitmapAsync(); if (bitmapImage is not null) Icon = bitmapImage; } public override int GetHashCode() => (Path, Name).GetHashCode(); public override bool Equals(object? other) => other is RecentItem item && Equals(item); public bool Equals(RecentItem? other) => other is not null && other.Name == Name && other.Path == Path; public unsafe void Dispose() { ShellItem.Dispose(); } } }
RecentItem
csharp
dotnet__efcore
test/EFCore.Specification.Tests/ModelBuilding101ManyToManyTestBase.cs
{ "start": 24252, "end": 24441 }
public class ____ { public int PostId { get; set; } public int TagId { get; set; } public DateTime CreatedOn { get; set; } }
PostTag
csharp
CommunityToolkit__Maui
src/CommunityToolkit.Maui.Core/Handlers/DrawingView/DrawingViewHandler.shared.cs
{ "start": 2070, "end": 8058 }
public partial class ____ : ViewHandler<IDrawingView, MauiDrawingView>, IDrawingViewHandler { IDrawingLineAdapter adapter = new DrawingLineAdapter(); /// <inheritdoc /> public void SetDrawingLineAdapter(IDrawingLineAdapter drawingLineAdapter) { adapter = drawingLineAdapter; } /// <summary> /// Action that's triggered when the DrawingView <see cref="IDrawingView.Lines"/> property changes. /// </summary> /// <param name="handler">An instance of <see cref="DrawingViewHandler"/>.</param> /// <param name="view">An instance of <see cref="IDrawingView"/>.</param> public static void MapLines(DrawingViewHandler handler, IDrawingView view) { handler.PlatformView.SetLines(view); } /// <summary> /// Action that's triggered when the DrawingView <see cref="IDrawingView.ShouldClearOnFinish"/> property changes. /// </summary> /// <param name="handler">An instance of <see cref="DrawingViewHandler"/>.</param> /// <param name="view">An instance of <see cref="IDrawingView"/>.</param> public static void MapShouldClearOnFinish(DrawingViewHandler handler, IDrawingView view) { handler.PlatformView.SetShouldClearOnFinish(view.ShouldClearOnFinish); } /// <summary> /// Action that's triggered when the DrawingView <see cref="IDrawingView.LineColor"/> property changes. /// </summary> /// <param name="handler">An instance of <see cref="DrawingViewHandler"/>.</param> /// <param name="view">An instance of <see cref="IDrawingView"/>.</param> public static void MapLineColor(DrawingViewHandler handler, IDrawingView view) { handler.PlatformView.SetLineColor(view.LineColor); } /// <summary> /// Action that's triggered when the DrawingView <see cref="IDrawingView.LineWidth"/> property changes. /// </summary> /// <param name="handler">An instance of <see cref="DrawingViewHandler"/>.</param> /// <param name="view">An instance of <see cref="IDrawingView"/>.</param> public static void MapLineWidth(DrawingViewHandler handler, IDrawingView view) { handler.PlatformView.SetLineWidth(view.LineWidth); } /// <summary> /// Action that's triggered when the DrawingView <see cref="IDrawingView.IsMultiLineModeEnabled"/> property changes. /// </summary> /// <param name="handler">An instance of <see cref="DrawingViewHandler"/>.</param> /// <param name="view">An instance of <see cref="IDrawingView"/>.</param> public static void MapIsMultiLineModeEnabled(DrawingViewHandler handler, IDrawingView view) { handler.PlatformView.SetIsMultiLineModeEnabled(view.IsMultiLineModeEnabled); } /// <summary> /// Action that's triggered when the DrawingView <see cref="IDrawingView.DrawAction"/> property changes. /// </summary> /// <param name="handler">An instance of <see cref="DrawingViewHandler"/>.</param> /// <param name="view">An instance of <see cref="IDrawingView"/>.</param> public static void MapDrawAction(DrawingViewHandler handler, IDrawingView view) { handler.PlatformView.SetDrawAction(view.DrawAction); } /// <summary> /// Action that's triggered when the DrawingView Background property changes. /// </summary> /// <param name="handler">An instance of <see cref="DrawingViewHandler"/>.</param> /// <param name="view">An instance of <see cref="IDrawingView"/>.</param> public static void MapDrawingViewBackground(DrawingViewHandler handler, IDrawingView view) { handler.PlatformView.SetPaint(view.Background ?? new SolidPaint(DrawingViewDefaults.BackgroundColor)); } /// <inheritdoc /> protected override void ConnectHandler(MauiDrawingView platformView) { base.ConnectHandler(platformView); platformView.Initialize(); platformView.DrawingStarted += OnPlatformViewDrawingStarted; platformView.DrawingCancelled += OnPlatformViewDrawingCancelled; platformView.Drawing += OnPlatformViewDrawing; platformView.DrawingLineCompleted += OnPlatformViewDrawingLineCompleted; VirtualView.Lines.CollectionChanged += OnVirtualViewLinesCollectionChanged; platformView.Lines.CollectionChanged += OnPlatformViewLinesCollectionChanged; } /// <inheritdoc /> protected override void DisconnectHandler(MauiDrawingView platformView) { platformView.DrawingStarted -= OnPlatformViewDrawingStarted; platformView.DrawingCancelled -= OnPlatformViewDrawingCancelled; platformView.Drawing -= OnPlatformViewDrawing; platformView.DrawingLineCompleted -= OnPlatformViewDrawingLineCompleted; VirtualView.Lines.CollectionChanged -= OnVirtualViewLinesCollectionChanged; platformView.Lines.CollectionChanged -= OnPlatformViewLinesCollectionChanged; platformView.CleanUp(); base.DisconnectHandler(platformView); } /// <inheritdoc /> #if ANDROID protected override MauiDrawingView CreatePlatformView() => new(Context); #else protected override MauiDrawingView CreatePlatformView() => new(); #endif void OnPlatformViewDrawingLineCompleted(object? sender, MauiDrawingLineCompletedEventArgs e) { var drawingLine = adapter.ConvertMauiDrawingLine(e.Line); VirtualView.OnDrawingLineCompleted(drawingLine); } void OnPlatformViewDrawing(object? sender, MauiOnDrawingEventArgs e) { VirtualView.OnPointDrawn(e.Point); } void OnPlatformViewDrawingStarted(object? sender, MauiDrawingStartedEventArgs e) { VirtualView.OnDrawingLineStarted(e.Point); } void OnPlatformViewDrawingCancelled(object? sender, EventArgs e) { VirtualView.OnDrawingLineCancelled(); } void OnVirtualViewLinesCollectionChanged(object? sender, NotifyCollectionChangedEventArgs e) { PlatformView.Lines.CollectionChanged -= OnPlatformViewLinesCollectionChanged; PlatformView.SetLines(VirtualView); PlatformView.Lines.CollectionChanged += OnPlatformViewLinesCollectionChanged; } void OnPlatformViewLinesCollectionChanged(object? sender, NotifyCollectionChangedEventArgs e) { VirtualView.Lines.CollectionChanged -= OnVirtualViewLinesCollectionChanged; VirtualView.SetLines(PlatformView, adapter); VirtualView.Lines.CollectionChanged += OnVirtualViewLinesCollectionChanged; } } #endif
DrawingViewHandler
csharp
dotnet__machinelearning
src/Microsoft.ML.CodeGenerator/CodeGenerator/CSharp/CSharpCodeFile.cs
{ "start": 412, "end": 1191 }
internal class ____ : ICSharpFile { private string _file; public string File { get => _file; set { _file = Utils.FormatCode(value); } } public string Name { get; set; } /// <summary> /// Write File To Disk /// </summary> /// <param name="location">full path of destinate directory</param> public void WriteToDisk(string location) { var extension = Path.GetExtension(Name); if (extension != ".cs") { throw new Exception("CSharp file extesion must be .cs"); } Utilities.Utils.WriteOutputToFiles(File, Name, location); } } }
CSharpCodeFile
csharp
grandnode__grandnode2
src/Tests/Grand.Business.Catalog.Tests/Services/Discounts/DiscountServiceTests.cs
{ "start": 762, "end": 28943 }
public class ____ { private MemoryCacheBase _cacheBase; private DiscountService _dicountService; private IEnumerable<IDiscountAmountProvider> _discountAmountProviders; private IRepository<DiscountCoupon> _discountCouponRepository; private DiscountProviderLoader _discountProviderLoader; private IEnumerable<IDiscountProvider> _discountProviders; private IRepository<DiscountUsageHistory> _discountUsageHistoryRepository; private DiscountValidationService _discountValidationService; private GetDiscountAmountProviderHandler _getDiscountAmountProviderHandler; private Mock<IMediator> _mediatorMock; private IRepository<Discount> _repository; private Mock<IWorkContext> _workContextMock; private Mock<IStoreContext> _storeContextMock; private GetDiscountUsageHistoryQueryHandler handler; [TestInitialize] public void InitializeTests() { _repository = new MongoDBRepositoryTest<Discount>(); _discountCouponRepository = new MongoDBRepositoryTest<DiscountCoupon>(); _discountUsageHistoryRepository = new MongoDBRepositoryTest<DiscountUsageHistory>(); _workContextMock = new Mock<IWorkContext>(); _storeContextMock = new Mock<IStoreContext>(); _storeContextMock.Setup(c => c.CurrentStore).Returns(() => new Store { Id = "" }); _workContextMock.Setup(c => c.CurrentCustomer).Returns(() => new Customer()); _mediatorMock = new Mock<IMediator>(); _cacheBase = new MemoryCacheBase(MemoryCacheTest.Get(), _mediatorMock.Object, new CacheConfig { DefaultCacheTimeMinutes = 1 }); _discountProviders = new List<IDiscountProvider> { new DiscountProviderTest() }; _discountAmountProviders = new List<IDiscountAmountProvider> { new DiscountAmountProviderTests() }; _discountProviderLoader = new DiscountProviderLoader(_discountProviders, _discountAmountProviders); _discountValidationService = new DiscountValidationService(_discountProviderLoader, _discountCouponRepository, _mediatorMock.Object); _dicountService = new DiscountService(_cacheBase, _repository, _discountCouponRepository, _discountUsageHistoryRepository, _mediatorMock.Object, new AccessControlConfig()); handler = new GetDiscountUsageHistoryQueryHandler(_discountUsageHistoryRepository); _getDiscountAmountProviderHandler = new GetDiscountAmountProviderHandler(_discountProviderLoader); } [TestMethod] public async Task GetDiscountByIdTest() { //Arrange var discount = new Discount { Name = "test" }; await _dicountService.InsertDiscount(discount); //Act var result = await _dicountService.GetDiscountById(discount.Id); //Assert Assert.IsNotNull(result); Assert.AreEqual("test", result.Name); } [TestMethod] public async Task GetAllDiscountsTest() { //Arrange var discount1 = new Discount { Name = "test1", IsEnabled = true }; await _dicountService.InsertDiscount(discount1); var discount2 = new Discount { Name = "test2", IsEnabled = true }; await _dicountService.InsertDiscount(discount2); //Act var result = await _dicountService.GetDiscountsQuery(null); //Assert Assert.IsNotNull(result); Assert.AreEqual(2, result.Count); } [TestMethod] public async Task InsertDiscountTest() { //Arrange var discount = new Discount { Name = "test" }; //Act await _dicountService.InsertDiscount(discount); //Assert Assert.IsNotNull(_repository.Table.FirstOrDefault(x => x.Name == "test")); Assert.AreEqual("test", _repository.Table.FirstOrDefault(x => x.Name == "test").Name); } [TestMethod] public async Task UpdateDiscountTest() { //Arrange var discount = new Discount { Name = "test" }; await _dicountService.InsertDiscount(discount); //Act discount.Name = "test2"; await _dicountService.UpdateDiscount(discount); //Assert Assert.IsNotNull(_repository.Table.FirstOrDefault(x => x.Name == "test2")); Assert.AreEqual("test2", _repository.Table.FirstOrDefault(x => x.Name == "test2").Name); } [TestMethod] public async Task DeleteDiscountTest() { //Arrange var discount = new Discount { Name = "test" }; await _dicountService.InsertDiscount(discount); //Act await _dicountService.DeleteDiscount(discount); //Assert Assert.IsNull(_repository.Table.FirstOrDefault(x => x.Name == "test")); } [TestMethod] public void LoadDiscountProviderBySystemNameTest_NotNull() { //Act var provider = _discountProviderLoader.LoadDiscountProviderByRuleSystemName("RuleSystemName"); //Assert Assert.IsNotNull(provider); } [TestMethod] public void LoadDiscountProviderBySystemNameTest_Null() { //Act var provider = _discountProviderLoader.LoadDiscountProviderByRuleSystemName("RuleSystemName2"); //Assert Assert.IsNull(provider); } [TestMethod] public void LoadAllDiscountProvidersTest() { //Act var providers = _discountProviderLoader.LoadAllDiscountProviders(); //Assert Assert.AreEqual(1, providers.Count); } [TestMethod] public async Task GetDiscountByCouponCodeTest() { //Arrange var discount = new Discount { Name = "test", IsEnabled = true }; await _dicountService.InsertDiscount(discount); var discountCoupon = new DiscountCoupon { CouponCode = "TEST123", DiscountId = discount.Id }; await _discountCouponRepository.InsertAsync(discountCoupon); //Act var coupon = await _dicountService.GetDiscountByCouponCode("TEST123"); //Assert Assert.IsNotNull(coupon); Assert.AreEqual(discount.Id, coupon.Id); } [TestMethod] public async Task GetAllCouponCodesByDiscountIdTest() { //Arrange var discount = new Discount { Name = "test", IsEnabled = true }; await _dicountService.InsertDiscount(discount); var discountCoupon = new DiscountCoupon { CouponCode = "TEST123", DiscountId = discount.Id }; await _discountCouponRepository.InsertAsync(discountCoupon); var discountCoupon1 = new DiscountCoupon { CouponCode = "TEST124", DiscountId = discount.Id }; await _discountCouponRepository.InsertAsync(discountCoupon1); var discountCoupon2 = new DiscountCoupon { CouponCode = "TEST125", DiscountId = "id" }; await _discountCouponRepository.InsertAsync(discountCoupon2); //Act var coupon = await _dicountService.GetAllCouponCodesByDiscountId(discount.Id); //Assert Assert.AreEqual(2, coupon.Count); } [TestMethod] public async Task GetDiscountCodeByIdTest() { //Arrange var discount = new Discount { Name = "test", IsEnabled = true }; await _dicountService.InsertDiscount(discount); var discountCoupon = new DiscountCoupon { CouponCode = "TEST123", DiscountId = discount.Id }; await _discountCouponRepository.InsertAsync(discountCoupon); var discountCoupon1 = new DiscountCoupon { CouponCode = "TEST124", DiscountId = discount.Id }; await _discountCouponRepository.InsertAsync(discountCoupon1); var discountCoupon2 = new DiscountCoupon { CouponCode = "TEST125", DiscountId = "id" }; await _discountCouponRepository.InsertAsync(discountCoupon2); //Act var coupon = await _dicountService.GetDiscountCodeById(discountCoupon.Id); //Assert Assert.IsNotNull(coupon); Assert.AreEqual("TEST123", coupon.CouponCode); } [TestMethod] public async Task GetDiscountCodeByCodeTest() { //Arrange var discount = new Discount { Name = "test", IsEnabled = true }; await _dicountService.InsertDiscount(discount); var discountCoupon = new DiscountCoupon { CouponCode = "TEST123", DiscountId = discount.Id }; await _discountCouponRepository.InsertAsync(discountCoupon); var discountCoupon1 = new DiscountCoupon { CouponCode = "TEST124", DiscountId = discount.Id }; await _discountCouponRepository.InsertAsync(discountCoupon1); var discountCoupon2 = new DiscountCoupon { CouponCode = "TEST125", DiscountId = "id" }; await _discountCouponRepository.InsertAsync(discountCoupon2); //Act var coupon = await _dicountService.GetDiscountCodeByCode(discountCoupon.CouponCode); //Assert Assert.IsNotNull(coupon); Assert.AreEqual("TEST123", coupon.CouponCode); } [TestMethod] public async Task DeleteDiscountCouponTest() { //Arrange var discount = new Discount { Name = "test", IsEnabled = true }; await _dicountService.InsertDiscount(discount); var discountCoupon = new DiscountCoupon { CouponCode = "TEST123", DiscountId = discount.Id }; await _discountCouponRepository.InsertAsync(discountCoupon); var discountCoupon1 = new DiscountCoupon { CouponCode = "TEST124", DiscountId = discount.Id }; await _discountCouponRepository.InsertAsync(discountCoupon1); var discountCoupon2 = new DiscountCoupon { CouponCode = "TEST125", DiscountId = "id" }; await _discountCouponRepository.InsertAsync(discountCoupon2); //Act await _dicountService.DeleteDiscountCoupon(discountCoupon); //Assert Assert.IsNull(_discountCouponRepository.Table.FirstOrDefault(x => x.Id == discountCoupon.Id)); } [TestMethod] public async Task InsertDiscountCouponTest() { //Arrange var discount = new Discount { Name = "test", IsEnabled = true }; await _dicountService.InsertDiscount(discount); var discountCoupon = new DiscountCoupon { CouponCode = "TEST123", DiscountId = discount.Id }; //Act await _discountCouponRepository.InsertAsync(discountCoupon); //Assert Assert.IsNotNull(_discountCouponRepository.Table.FirstOrDefault(x => x.Id == discountCoupon.Id)); } [TestMethod] public async Task DiscountCouponSetAsUsedTest() { //Arrange var discount = new Discount { Name = "test", IsEnabled = true }; await _dicountService.InsertDiscount(discount); var discountCoupon = new DiscountCoupon { CouponCode = "TEST123", DiscountId = discount.Id }; await _discountCouponRepository.InsertAsync(discountCoupon); //Act await _dicountService.DiscountCouponSetAsUsed("TEST123", true); //Assert Assert.IsNotNull(_discountCouponRepository.Table.FirstOrDefault(x => x.Id == discountCoupon.Id)); Assert.IsTrue(_discountCouponRepository.Table.FirstOrDefault(x => x.Id == discountCoupon.Id).Used); } [TestMethod] public async Task CancelDiscountTest() { //Arrange var discount = new Discount { Name = "test", IsEnabled = true }; await _dicountService.InsertDiscount(discount); var discountCoupon = new DiscountCoupon { CouponCode = "TEST123", DiscountId = discount.Id, Used = true }; await _discountCouponRepository.InsertAsync(discountCoupon); var discountUsageHistory = new DiscountUsageHistory { DiscountId = discount.Id, OrderId = "123", CouponCode = "TEST123" }; await _discountUsageHistoryRepository.InsertAsync(discountUsageHistory); //Act await _dicountService.CancelDiscount("123"); //Assert Assert.IsTrue(_discountUsageHistoryRepository.Table.FirstOrDefault(x => x.Id == discountUsageHistory.Id) .Canceled); Assert.IsFalse(_discountCouponRepository.Table.FirstOrDefault(x => x.Id == discountCoupon.Id).Used); } [TestMethod] public async Task ValidateDiscountTest_Valid_CouponCodesToValidate() { //Arrange var discount = new Discount { Name = "test", IsEnabled = true, CurrencyCode = "USD" }; await _dicountService.InsertDiscount(discount); var discountCoupon = new DiscountCoupon { CouponCode = "TEST123", DiscountId = discount.Id, Used = true }; await _discountCouponRepository.InsertAsync(discountCoupon); var customer = new Customer(); customer.UserFields.Add(new UserField { Key = SystemCustomerFieldNames.DiscountCoupons, Value = "TEST123", StoreId = "" }); //Act var result = await _discountValidationService.ValidateDiscount(discount, customer, new Store(), new Currency { CurrencyCode = "USD" }); //Assert Assert.IsTrue(result.IsValid); } [TestMethod] public async Task ValidateDiscountTest_InValid_CouponCodesToValidate() { //Arrange var discount = new Discount { Name = "test", IsEnabled = true, CurrencyCode = "USD", RequiresCouponCode = true }; await _dicountService.InsertDiscount(discount); var discountCoupon = new DiscountCoupon { CouponCode = "TEST123", DiscountId = discount.Id, Used = true }; await _discountCouponRepository.InsertAsync(discountCoupon); var customer = new Customer(); customer.UserFields.Add(new UserField { Key = SystemCustomerFieldNames.DiscountCoupons, Value = "TEST12", StoreId = "" }); //Act var result = await _discountValidationService.ValidateDiscount(discount, customer, new Store(), new Currency { CurrencyCode = "USD" }); //Assert Assert.IsFalse(result.IsValid); } [TestMethod] public async Task ValidateDiscountTest_InValid_CurrencyCode() { //Arrange var discount = new Discount { Name = "test", IsEnabled = true, CurrencyCode = "EUR" }; await _dicountService.InsertDiscount(discount); var discountCoupon = new DiscountCoupon { CouponCode = "TEST123", DiscountId = discount.Id, Used = true }; await _discountCouponRepository.InsertAsync(discountCoupon); var customer = new Customer(); customer.UserFields.Add(new UserField { Key = SystemCustomerFieldNames.DiscountCoupons, Value = "TEST12", StoreId = "" }); //Act var result = await _discountValidationService.ValidateDiscount(discount, customer, new Store(), new Currency { CurrencyCode = "USD" }); //Assert Assert.IsFalse(result.IsValid); } [TestMethod] public async Task ValidateDiscountTest_InValid_EndDateUtc() { //Arrange var discount = new Discount { Name = "test", IsEnabled = true, CurrencyCode = "USD", EndDateUtc = DateTime.UtcNow.AddDays(-1) }; await _dicountService.InsertDiscount(discount); var discountCoupon = new DiscountCoupon { CouponCode = "TEST123", DiscountId = discount.Id, Used = true }; await _discountCouponRepository.InsertAsync(discountCoupon); var customer = new Customer(); customer.UserFields.Add(new UserField { Key = SystemCustomerFieldNames.DiscountCoupons, Value = "TEST12", StoreId = "" }); //Act var result = await _discountValidationService.ValidateDiscount(discount, customer, new Store(), new Currency { CurrencyCode = "USD" }); //Assert Assert.IsFalse(result.IsValid); } [TestMethod] public async Task ValidateDiscountTest_InValid_Disable() { //Arrange var discount = new Discount { Name = "test", IsEnabled = false, CurrencyCode = "USD" }; await _dicountService.InsertDiscount(discount); var discountCoupon = new DiscountCoupon { CouponCode = "TEST123", DiscountId = discount.Id, Used = true }; await _discountCouponRepository.InsertAsync(discountCoupon); var customer = new Customer(); customer.UserFields.Add(new UserField { Key = SystemCustomerFieldNames.DiscountCoupons, Value = "TEST12", StoreId = "" }); //Act var result = await _discountValidationService.ValidateDiscount(discount, customer, new Store(), new Currency { CurrencyCode = "USD" }); //Assert Assert.IsFalse(result.IsValid); } [TestMethod] public async Task GetDiscountUsageHistoryByIdTest() { //Arrange var discount = new Discount { Name = "test", IsEnabled = true }; await _dicountService.InsertDiscount(discount); var discountCoupon = new DiscountCoupon { CouponCode = "TEST123", DiscountId = discount.Id, Used = true }; await _discountCouponRepository.InsertAsync(discountCoupon); var discountUsageHistory = new DiscountUsageHistory { DiscountId = discount.Id, OrderId = "123", CouponCode = "TEST123" }; await _discountUsageHistoryRepository.InsertAsync(discountUsageHistory); //Act await _dicountService.GetDiscountUsageHistoryById(discountUsageHistory.Id); //Assert Assert.IsNotNull(_discountUsageHistoryRepository.Table.FirstOrDefault(x => x.Id == discountUsageHistory.Id)); } [TestMethod] public async Task GetAllDiscountUsageHistoryTest() { //Arrange var discount = new Discount { Name = "test", IsEnabled = true }; await _dicountService.InsertDiscount(discount); var discountCoupon = new DiscountCoupon { CouponCode = "TEST123", DiscountId = discount.Id, Used = true }; await _discountCouponRepository.InsertAsync(discountCoupon); var discountUsageHistory = new DiscountUsageHistory { DiscountId = discount.Id, OrderId = "123", CouponCode = "TEST123" }; await _discountUsageHistoryRepository.InsertAsync(discountUsageHistory); var discountUsageHistory2 = new DiscountUsageHistory { DiscountId = discount.Id, OrderId = "124", CouponCode = "TEST123" }; await _discountUsageHistoryRepository.InsertAsync(discountUsageHistory2); //Act var usageHistory = await handler.Handle(new GetDiscountUsageHistoryQuery(), CancellationToken.None); //Assert Assert.AreEqual(2, usageHistory.Count); } [TestMethod] public async Task InsertDiscountUsageHistoryTest() { //Arrange var discount = new Discount { Name = "test", IsEnabled = true }; await _dicountService.InsertDiscount(discount); var discountCoupon = new DiscountCoupon { CouponCode = "TEST123", DiscountId = discount.Id, Used = true }; await _discountCouponRepository.InsertAsync(discountCoupon); var discountUsageHistory = new DiscountUsageHistory { DiscountId = discount.Id, OrderId = "123", CouponCode = "TEST123" }; await _discountUsageHistoryRepository.InsertAsync(discountUsageHistory); //Act var usageHistory = await _dicountService.GetDiscountUsageHistoryById(discountUsageHistory.Id); //Assert Assert.IsNotNull(usageHistory); Assert.AreEqual(discountUsageHistory.CouponCode, usageHistory.CouponCode); } [TestMethod] public async Task UpdateDiscountUsageHistoryTest() { //Arrange var discount = new Discount { Name = "test", IsEnabled = true }; await _dicountService.InsertDiscount(discount); var discountCoupon = new DiscountCoupon { CouponCode = "TEST123", DiscountId = discount.Id, Used = true }; await _discountCouponRepository.InsertAsync(discountCoupon); var discountUsageHistory = new DiscountUsageHistory { DiscountId = discount.Id, OrderId = "123", CouponCode = "TEST123" }; await _discountUsageHistoryRepository.InsertAsync(discountUsageHistory); //Act discountUsageHistory.OrderId = "12"; await _discountUsageHistoryRepository.UpdateAsync(discountUsageHistory); var usageHistory = await _dicountService.GetDiscountUsageHistoryById(discountUsageHistory.Id); //Assert Assert.IsNotNull(usageHistory); Assert.AreEqual(discountUsageHistory.OrderId, usageHistory.OrderId); } [TestMethod] public async Task DeleteDiscountUsageHistoryTest() { //Arrange var discount = new Discount { Name = "test", IsEnabled = true }; await _dicountService.InsertDiscount(discount); var discountCoupon = new DiscountCoupon { CouponCode = "TEST123", DiscountId = discount.Id, Used = true }; await _discountCouponRepository.InsertAsync(discountCoupon); var discountUsageHistory = new DiscountUsageHistory { DiscountId = discount.Id, OrderId = "123", CouponCode = "TEST123" }; await _discountUsageHistoryRepository.InsertAsync(discountUsageHistory); //Act await _discountUsageHistoryRepository.DeleteAsync(discountUsageHistory); var usageHistory = await _dicountService.GetDiscountUsageHistoryById(discountUsageHistory.Id); //Assert Assert.IsNull(usageHistory); } [TestMethod] public async Task GetDiscountAmountTest_global() { //Arrange var discount = new Discount { Name = "test", DiscountAmount = 10, CurrencyCode = "USD", IsEnabled = true }; await _dicountService.InsertDiscount(discount); //Act var discountamount = await _dicountService.GetDiscountAmount(discount, new Customer(), new Currency { CurrencyCode = "USD" }, new Product(), 100); //Assert Assert.AreEqual(discount.DiscountAmount, discountamount); } public async Task GetDiscountAmountTest_AssignedToAllProducts() { //Arrange var discount = new Discount { Name = "test", DiscountAmount = 10, CurrencyCode = "USD", IsEnabled = true, DiscountTypeId = DiscountType.AssignedToAllProducts }; await _dicountService.InsertDiscount(discount); //Act var discountamount = await _dicountService.GetDiscountAmount(discount, new Customer(), new Currency { CurrencyCode = "USD" }, new Product(), 100); //Assert Assert.AreEqual(discount.DiscountAmount, discountamount); } [TestMethod] public async Task GetPreferredDiscountTest() { //Arrange var discount1 = new Discount { Name = "test", DiscountAmount = 10, CurrencyCode = "USD", IsEnabled = true, DiscountTypeId = DiscountType.AssignedToAllProducts }; await _dicountService.InsertDiscount(discount1); var discount2 = new Discount { Name = "test", DiscountAmount = 20, CurrencyCode = "USD", IsEnabled = true, DiscountTypeId = DiscountType.AssignedToAllProducts }; await _dicountService.InsertDiscount(discount2); //Act var discountamount = await _dicountService.GetPreferredDiscount( new List<ApplyDiscount> { new() { DiscountId = discount1.Id, IsCumulative = false }, new() { DiscountId = discount2.Id, IsCumulative = false } }, new Customer(), new Currency { CurrencyCode = "USD" }, new Product(), 100); //Assert Assert.AreEqual(discount2.DiscountAmount, discountamount.discountAmount); } [TestMethod] public async Task GetPreferredDiscountTest_IsCumulative_True() { //Arrange var discount1 = new Discount { Name = "test", DiscountAmount = 10, CurrencyCode = "USD", IsEnabled = true, DiscountTypeId = DiscountType.AssignedToAllProducts }; await _dicountService.InsertDiscount(discount1); var discount2 = new Discount { Name = "test", DiscountAmount = 20, CurrencyCode = "USD", IsEnabled = true, DiscountTypeId = DiscountType.AssignedToAllProducts }; await _dicountService.InsertDiscount(discount2); //Act var discountamount = await _dicountService.GetPreferredDiscount( new List<ApplyDiscount> { new() { DiscountId = discount1.Id, IsCumulative = true }, new() { DiscountId = discount2.Id, IsCumulative = true } }, new Customer(), new Currency { CurrencyCode = "USD" }, new Product(), 100); //Assert Assert.AreEqual(discount1.DiscountAmount + discount2.DiscountAmount, discountamount.discountAmount); } [TestMethod] public async Task GetDiscountAmountProviderTest() { //Arrange var discount1 = new Discount { Name = "test", DiscountAmount = 10, CurrencyCode = "USD", IsEnabled = true, CalculateByPlugin = true, DiscountPluginName = "SampleDiscountAmountProvider", DiscountTypeId = DiscountType.AssignedToAllProducts }; await _dicountService.InsertDiscount(discount1); //Act var amount = await _getDiscountAmountProviderHandler.Handle( new GetDiscountAmountProvider(discount1, new Customer(), new Product(), new Currency(), 100), CancellationToken.None); //Assert Assert.AreEqual(9, amount); } [TestMethod] public void LoadDiscountAmountProviderBySystemNameTest() { //Act var discountProvider = _discountProviderLoader.LoadDiscountAmountProviderBySystemName("SampleDiscountAmountProvider"); //Assert Assert.IsNotNull(discountProvider); } [TestMethod] public void LoadDiscountAmountProvidersTest() { //Act var discountProviders = _discountProviderLoader.LoadDiscountAmountProviders(); //Assert Assert.AreEqual(1, discountProviders.Count); } }
DiscountServiceTests
csharp
moq__moq4
src/Moq/Matchers/ExpressionMatcher.cs
{ "start": 282, "end": 883 }
class ____ : IMatcher { Expression expression; public ExpressionMatcher(Expression expression) { this.expression = expression; } public bool Matches(object argument, Type parameterType) { return argument is Expression valueExpression && ExpressionComparer.Default.Equals(this.expression, valueExpression); } public void SetupEvaluatedSuccessfully(object argument, Type parameterType) { Debug.Assert(this.Matches(argument, parameterType)); } } }
ExpressionMatcher
csharp
nopSolutions__nopCommerce
src/Libraries/Nop.Services/Customers/CustomerService.cs
{ "start": 21686, "end": 22506 }
record ____ for background tasks /// </summary> /// <returns> /// A task that represents the asynchronous operation /// The task result contains a customer object /// </returns> public virtual async Task<Customer> GetOrCreateBackgroundTaskUserAsync() { var backgroundTaskUser = await GetCustomerBySystemNameAsync(NopCustomerDefaults.BackgroundTaskCustomerName); if (backgroundTaskUser is null) { var store = await _storeContext.GetCurrentStoreAsync(); //If for any reason the system user isn't in the database, then we add it backgroundTaskUser = new Customer { Email = "builtin@background-task-record.com", CustomerGuid = Guid.NewGuid(), AdminComment = "Built-in system
used
csharp
unoplatform__uno
src/Uno.UWP/Generated/3.0.0.0/Windows.ApplicationModel.Activation/LaunchActivatedEventArgs.cs
{ "start": 270, "end": 4693 }
public partial class ____ : global::Windows.ApplicationModel.Activation.ILaunchActivatedEventArgs, global::Windows.ApplicationModel.Activation.IActivatedEventArgs, global::Windows.ApplicationModel.Activation.IApplicationViewActivatedEventArgs, global::Windows.ApplicationModel.Activation.IPrelaunchActivatedEventArgs, global::Windows.ApplicationModel.Activation.IViewSwitcherProvider, global::Windows.ApplicationModel.Activation.ILaunchActivatedEventArgs2, global::Windows.ApplicationModel.Activation.IActivatedEventArgsWithUser { // Skipping already declared property Kind // Skipping already declared property PreviousExecutionState // Skipping already declared property SplashScreen #if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")] public global::Windows.System.User User { get { throw new global::System.NotImplementedException("The member User LaunchActivatedEventArgs.User is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=User%20LaunchActivatedEventArgs.User"); } } #endif // Skipping already declared property CurrentlyShownApplicationViewId // Skipping already declared property Arguments // Skipping already declared property TileId #if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")] public global::Windows.ApplicationModel.Activation.TileActivatedInfo TileActivatedInfo { get { throw new global::System.NotImplementedException("The member TileActivatedInfo LaunchActivatedEventArgs.TileActivatedInfo is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=TileActivatedInfo%20LaunchActivatedEventArgs.TileActivatedInfo"); } } #endif // Skipping already declared property PrelaunchActivated #if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")] public global::Windows.UI.ViewManagement.ActivationViewSwitcher ViewSwitcher { get { throw new global::System.NotImplementedException("The member ActivationViewSwitcher LaunchActivatedEventArgs.ViewSwitcher is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=ActivationViewSwitcher%20LaunchActivatedEventArgs.ViewSwitcher"); } } #endif // Forced skipping of method Windows.ApplicationModel.Activation.LaunchActivatedEventArgs.Arguments.get // Forced skipping of method Windows.ApplicationModel.Activation.LaunchActivatedEventArgs.TileId.get // Forced skipping of method Windows.ApplicationModel.Activation.LaunchActivatedEventArgs.Kind.get // Forced skipping of method Windows.ApplicationModel.Activation.LaunchActivatedEventArgs.PreviousExecutionState.get // Forced skipping of method Windows.ApplicationModel.Activation.LaunchActivatedEventArgs.SplashScreen.get // Forced skipping of method Windows.ApplicationModel.Activation.LaunchActivatedEventArgs.CurrentlyShownApplicationViewId.get // Forced skipping of method Windows.ApplicationModel.Activation.LaunchActivatedEventArgs.PrelaunchActivated.get // Forced skipping of method Windows.ApplicationModel.Activation.LaunchActivatedEventArgs.ViewSwitcher.get // Forced skipping of method Windows.ApplicationModel.Activation.LaunchActivatedEventArgs.TileActivatedInfo.get // Forced skipping of method Windows.ApplicationModel.Activation.LaunchActivatedEventArgs.User.get // Processing: Windows.ApplicationModel.Activation.ILaunchActivatedEventArgs // Processing: Windows.ApplicationModel.Activation.IActivatedEventArgs // Processing: Windows.ApplicationModel.Activation.IApplicationViewActivatedEventArgs // Processing: Windows.ApplicationModel.Activation.IPrelaunchActivatedEventArgs // Processing: Windows.ApplicationModel.Activation.IViewSwitcherProvider // Processing: Windows.ApplicationModel.Activation.ILaunchActivatedEventArgs2 // Processing: Windows.ApplicationModel.Activation.IActivatedEventArgsWithUser } }
LaunchActivatedEventArgs
csharp
ChilliCream__graphql-platform
src/HotChocolate/MongoDb/test/Data.MongoDb.Filters.Tests/SchemaCache.cs
{ "start": 649, "end": 963 }
class ____ TType : FilterInputType<T> { (Type, Type, T[] entites) key = (typeof(T), typeof(TType), entities); return _cache.GetOrAdd( key, k => CreateSchema<T, TType>(entities, _resource, withPaging: withPaging)); } public void Dispose() { } }
where
csharp
dotnet__efcore
src/EFCore/Metadata/Builders/IConventionComplexPropertyBuilder.cs
{ "start": 719, "end": 2488 }
public interface ____ : IConventionPropertyBaseBuilder<IConventionComplexPropertyBuilder> { /// <summary> /// Gets the property being configured. /// </summary> new IConventionComplexProperty Metadata { get; } /// <summary> /// Configures whether this property must have a value assigned or <see langword="null" /> is a valid value. /// A property can only be configured as non-required if it is based on a CLR type that can be /// assigned <see langword="null" />. /// </summary> /// <param name="required"> /// A value indicating whether the property is required. /// <see langword="null" /> to reset to default. /// </param> /// <param name="fromDataAnnotation">Indicates whether the configuration was specified using a data annotation.</param> /// <returns> /// The same builder instance if the requiredness was configured, /// <see langword="null" /> otherwise. /// </returns> IConventionComplexPropertyBuilder? IsRequired(bool? required, bool fromDataAnnotation = false); /// <summary> /// Returns a value indicating whether this property requiredness can be configured /// from the current configuration source. /// </summary> /// <param name="required"> /// A value indicating whether the property is required. /// <see langword="null" /> to reset to default. /// </param> /// <param name="fromDataAnnotation">Indicates whether the configuration was specified using a data annotation.</param> /// <returns><see langword="true" /> if the property requiredness can be configured.</returns> bool CanSetIsRequired(bool? required, bool fromDataAnnotation = false); }
IConventionComplexPropertyBuilder
csharp
AutoFixture__AutoFixture
Src/IdiomsUnitTest/EqualsSelfAssertionTest.cs
{ "start": 2965, "end": 3295 }
private class ____ { public override bool Equals(object obj) { if (obj != null && object.ReferenceEquals(this, obj)) return false; throw new Exception(); } } #pragma warning restore 659
IllBehavedEqualsSelfObjectOverride
csharp
bitwarden__server
src/Core/AdminConsole/OrganizationFeatures/OrganizationUsers/InviteUsers/Validation/Organization/Errors.cs
{ "start": 407, "end": 608 }
public record ____(InviteOrganization InvalidRequest) : Error<InviteOrganization>(Code, InvalidRequest) { public const string Code = "No subscription found."; }
OrganizationNoSubscriptionFoundError
csharp
bitwarden__server
src/Core/Context/ICurrentContext.cs
{ "start": 707, "end": 3997 }
public interface ____ { HttpContext HttpContext { get; set; } Guid? UserId { get; set; } User User { get; set; } string DeviceIdentifier { get; set; } DeviceType? DeviceType { get; set; } string IpAddress { get; set; } string CountryName { get; set; } List<CurrentContextOrganization> Organizations { get; set; } Guid? InstallationId { get; set; } Guid? OrganizationId { get; set; } IdentityClientType IdentityClientType { get; set; } string ClientId { get; set; } Version ClientVersion { get; set; } bool ClientVersionIsPrerelease { get; set; } Task BuildAsync(HttpContext httpContext, GlobalSettings globalSettings); Task BuildAsync(ClaimsPrincipal user, GlobalSettings globalSettings); Task SetContextAsync(ClaimsPrincipal user); Task<bool> OrganizationUser(Guid orgId); Task<bool> OrganizationAdmin(Guid orgId); Task<bool> OrganizationOwner(Guid orgId); Task<bool> OrganizationCustom(Guid orgId); Task<bool> AccessEventLogs(Guid orgId); Task<bool> AccessImportExport(Guid orgId); Task<bool> AccessReports(Guid orgId); [Obsolete("Deprecated. Use an authorization handler checking the specific permissions required instead.")] Task<bool> EditAnyCollection(Guid orgId); [Obsolete("Deprecated. Use an authorization handler checking the specific permissions required instead.")] Task<bool> ViewAllCollections(Guid orgId); Task<bool> ManageGroups(Guid orgId); Task<bool> ManagePolicies(Guid orgId); Task<bool> ManageSso(Guid orgId); Task<bool> ManageUsers(Guid orgId); Task<bool> AccessMembersTab(Guid orgId); Task<bool> ManageScim(Guid orgId); Task<bool> ManageResetPassword(Guid orgId); Task<bool> ViewSubscription(Guid orgId); Task<bool> EditSubscription(Guid orgId); Task<bool> EditPaymentMethods(Guid orgId); Task<bool> ViewBillingHistory(Guid orgId); /// <summary> /// Returns true if the current user is a member of a provider that manages the specified organization. /// This generally gives the user administrative privileges for the organization. /// </summary> /// <param name="orgId"></param> /// <returns></returns> Task<bool> ProviderUserForOrgAsync(Guid orgId); /// <summary> /// Returns true if the current user is a Provider Admin of the specified provider. /// </summary> bool ProviderProviderAdmin(Guid providerId); /// <summary> /// Returns true if the current user is a member of the specified provider (with any role). /// </summary> bool ProviderUser(Guid providerId); bool ProviderManageUsers(Guid providerId); bool ProviderAccessEventLogs(Guid providerId); bool AccessProviderOrganizations(Guid providerId); bool ManageProviderOrganizations(Guid providerId); Task<ICollection<CurrentContextOrganization>> OrganizationMembershipAsync( IOrganizationUserRepository organizationUserRepository, Guid userId); Task<ICollection<CurrentContextProvider>> ProviderMembershipAsync( IProviderUserRepository providerUserRepository, Guid userId); Task<Guid?> ProviderIdForOrg(Guid orgId); bool AccessSecretsManager(Guid organizationId); CurrentContextOrganization? GetOrganization(Guid orgId); }
ICurrentContext
csharp
ChilliCream__graphql-platform
src/HotChocolate/Fusion-vnext/test/Fusion.AspNetCore.Tests/FusionTestBase.cs
{ "start": 8993, "end": 10249 }
private class ____ : IHttpClientFactory { private readonly Dictionary<string, TestServerRegistration> _registrations; public Factory(IEnumerable<TestServerRegistration> registrations) { _registrations = registrations.ToDictionary(r => r.Name, r => r); } public HttpClient CreateClient(string name) { if (_registrations.TryGetValue(name, out var registration)) { HttpClient client; if (registration.Options.IsOffline) { client = new HttpClient(new ErrorHandler()); } else if (registration.Options.IsTimingOut) { client = new HttpClient(new TimeoutHandler()); } else { client = registration.Server.CreateClient(); } registration.Options.ConfigureHttpClient?.Invoke(client); client.DefaultRequestHeaders.AddGraphQLPreflight(); return client; } throw new InvalidOperationException( $"No test server registered with the name: {name}"); }
Factory
csharp
dotnet__efcore
test/EFCore.Cosmos.Tests/Extensions/CosmosBuilderExtensionsTest.cs
{ "start": 269, "end": 9578 }
public class ____ { [ConditionalFact] public void Can_get_and_set_collection_name() { var modelBuilder = CreateConventionModelBuilder(); var entityType = modelBuilder .Entity<Customer>(); Assert.Equal(nameof(DbContext), entityType.Metadata.GetContainer()); entityType.ToContainer("Customizer"); Assert.Equal("Customizer", entityType.Metadata.GetContainer()); entityType.ToContainer(null); Assert.Equal(nameof(DbContext), entityType.Metadata.GetContainer()); modelBuilder.HasDefaultContainer("Unicorn"); Assert.Equal("Unicorn", entityType.Metadata.GetContainer()); } [ConditionalFact] public void Can_get_and_set_partition_key_name() { var modelBuilder = CreateConventionModelBuilder(); var entityTypeBuilder = modelBuilder.Entity<Customer>(); var entityType = entityTypeBuilder.Metadata; ((IConventionEntityType)entityType).Builder.HasPartitionKey(["pk"]); Assert.Equal("pk", entityType.GetPartitionKeyPropertyNames().Single()); Assert.Equal( ConfigurationSource.Convention, ((IConventionEntityType)entityType).GetPartitionKeyPropertyNamesConfigurationSource()); #pragma warning disable CS0618 // Type or member is obsolete ((IConventionEntityType)entityType).Builder.HasPartitionKey("pk"); Assert.Equal("pk", entityType.GetPartitionKeyPropertyName()); Assert.Equal( ConfigurationSource.Convention, ((IConventionEntityType)entityType).GetPartitionKeyPropertyNameConfigurationSource()); #pragma warning restore CS0618 // Type or member is obsolete entityTypeBuilder.HasPartitionKey("pk"); Assert.Equal("pk", entityType.GetPartitionKeyPropertyNames().Single()); Assert.Equal( ConfigurationSource.Explicit, ((IConventionEntityType)entityType).GetPartitionKeyPropertyNamesConfigurationSource()); Assert.False(((IConventionEntityType)entityType).Builder.CanSetPartitionKey(["partition"])); #pragma warning disable CS0618 // Type or member is obsolete Assert.Equal("pk", entityType.GetPartitionKeyPropertyName()); Assert.Equal( ConfigurationSource.Explicit, ((IConventionEntityType)entityType).GetPartitionKeyPropertyNameConfigurationSource()); Assert.False(((IConventionEntityType)entityType).Builder.CanSetPartitionKey("partition")); #pragma warning restore CS0618 // Type or member is obsolete entityTypeBuilder.HasPartitionKey(null); Assert.Empty(entityType.GetPartitionKeyPropertyNames()); Assert.Null(((IConventionEntityType)entityType).GetPartitionKeyPropertyNamesConfigurationSource()); #pragma warning disable CS0618 // Type or member is obsolete Assert.Null(entityType.GetPartitionKeyPropertyName()); Assert.Null(((IConventionEntityType)entityType).GetPartitionKeyPropertyNameConfigurationSource()); #pragma warning restore CS0618 // Type or member is obsolete } [ConditionalFact] public void Can_get_and_set_hierarchical_partition_key_name() { var modelBuilder = CreateConventionModelBuilder(); var entityTypeBuilder = modelBuilder.Entity<Customer>(); var entityType = entityTypeBuilder.Metadata; ((IConventionEntityType)entityType).Builder.HasPartitionKey(["pk1", "pk2", "pk3", "pk4", "pk5"]); Assert.Equal(["pk1", "pk2", "pk3", "pk4", "pk5"], entityType.GetPartitionKeyPropertyNames()); Assert.Equal( ConfigurationSource.Convention, ((IConventionEntityType)entityType).GetPartitionKeyPropertyNamesConfigurationSource()); entityTypeBuilder.HasPartitionKey("pk1", "pk2", "pk3", "pk4", "pk5"); Assert.Equal(["pk1", "pk2", "pk3", "pk4", "pk5"], entityType.GetPartitionKeyPropertyNames()); Assert.Equal( ConfigurationSource.Explicit, ((IConventionEntityType)entityType).GetPartitionKeyPropertyNamesConfigurationSource()); Assert.False(((IConventionEntityType)entityType).Builder.CanSetPartitionKey(["partition", "p2", "p3"])); entityTypeBuilder.HasPartitionKey(null); Assert.Empty(entityType.GetPartitionKeyPropertyNames()); Assert.Null(((IConventionEntityType)entityType).GetPartitionKeyPropertyNamesConfigurationSource()); } [ConditionalFact] public void Default_container_name_is_used_if_not_set() { var modelBuilder = CreateConventionModelBuilder(); modelBuilder .Entity<Customer>(); var entityType = modelBuilder.Model.FindEntityType(typeof(Customer))!; modelBuilder.HasDefaultContainer(null); Assert.Equal(nameof(Customer), entityType.GetContainer()); Assert.Null(modelBuilder.Model.GetDefaultContainer()); modelBuilder.HasDefaultContainer("db0"); Assert.Equal("db0", entityType.GetContainer()); Assert.Equal("db0", modelBuilder.Model.GetDefaultContainer()); modelBuilder .Entity<Customer>() .ToContainer("db1"); Assert.Equal("db1", entityType.GetContainer()); } [ConditionalFact] public void Default_discriminator_can_be_removed() { var modelBuilder = CreateConventionModelBuilder(); modelBuilder.Entity<Customer>(); var entityType = modelBuilder.Model.FindEntityType(typeof(Customer))!; Assert.Equal("$type", entityType.FindDiscriminatorProperty()!.Name); Assert.Equal(nameof(Customer), entityType.GetDiscriminatorValue()); modelBuilder.Entity<Customer>().HasNoDiscriminator(); Assert.Null(entityType.FindDiscriminatorProperty()); Assert.Null(entityType.GetDiscriminatorValue()); modelBuilder.Entity<Customer>().HasBaseType<object>(); Assert.Equal("$type", entityType.FindDiscriminatorProperty()!.Name); Assert.Equal(nameof(Customer), entityType.GetDiscriminatorValue()); modelBuilder.Entity<Customer>().HasBaseType((string)null); Assert.Null(entityType.FindDiscriminatorProperty()); } [ConditionalFact] public void Can_set_etag_concurrency_entity() { var modelBuilder = CreateConventionModelBuilder(); modelBuilder.Entity<Customer>().UseETagConcurrency(); var model = modelBuilder.Model; var etagProperty = model.FindEntityType(typeof(Customer).FullName!)!.FindProperty("_etag"); Assert.NotNull(etagProperty); Assert.Equal(ValueGenerated.OnAddOrUpdate, etagProperty.ValueGenerated); Assert.True(etagProperty.IsConcurrencyToken); } [ConditionalFact] public void Can_set_etag_concurrency_property() { var modelBuilder = CreateConventionModelBuilder(); modelBuilder.Entity<Customer>().Property(x => x.ETag).IsETagConcurrency(); var model = modelBuilder.Model; var etagProperty = model.FindEntityType(typeof(Customer).FullName!)!.FindProperty("ETag"); Assert.NotNull(etagProperty); Assert.Equal(ValueGenerated.OnAddOrUpdate, etagProperty.ValueGenerated); Assert.True(etagProperty.IsConcurrencyToken); Assert.Equal("_etag", etagProperty.GetJsonPropertyName()); } [ConditionalFact] public void Can_use_convention_trigger_builder() { var modelBuilder = CreateConventionModelBuilder(); var entityType = modelBuilder.Entity<Customer>().Metadata; var trigger = entityType.AddTrigger("TestTrigger"); var conventionTrigger = (IConventionTrigger)trigger; var triggerBuilder = conventionTrigger.Builder; Assert.NotNull(triggerBuilder.HasTriggerType(TriggerType.Pre, fromDataAnnotation: true)); Assert.Equal(TriggerType.Pre, trigger.GetTriggerType()); Assert.Equal(ConfigurationSource.DataAnnotation, conventionTrigger.GetTriggerTypeConfigurationSource()); Assert.Null(triggerBuilder.HasTriggerType(TriggerType.Post, fromDataAnnotation: false)); Assert.Equal(TriggerType.Pre, trigger.GetTriggerType()); Assert.Equal(ConfigurationSource.DataAnnotation, conventionTrigger.GetTriggerTypeConfigurationSource()); Assert.NotNull(triggerBuilder.HasTriggerType(TriggerType.Post, fromDataAnnotation: true)); Assert.Equal(TriggerType.Post, trigger.GetTriggerType()); Assert.Equal(ConfigurationSource.DataAnnotation, conventionTrigger.GetTriggerTypeConfigurationSource()); } [ConditionalFact] public void Can_create_trigger() { var modelBuilder = CreateConventionModelBuilder(); TriggerBuilder triggerBuilder = null!; modelBuilder.Entity<Customer>(entity => { triggerBuilder = entity.HasTrigger("TestTrigger", TriggerType.Pre, TriggerOperation.Create); }); var entityType = modelBuilder.Model.FindEntityType(typeof(Customer))!; var trigger = entityType.FindDeclaredTrigger("TestTrigger")!; Assert.Equal(TriggerType.Pre, trigger.GetTriggerType()); Assert.Equal(TriggerOperation.Create, trigger.GetTriggerOperation()); } protected virtual ModelBuilder CreateConventionModelBuilder() => CosmosTestHelpers.Instance.CreateConventionBuilder();
CosmosBuilderExtensionsTest
csharp
smartstore__Smartstore
src/Smartstore.Core/Data/Migrations/MigrationAssembly.cs
{ "start": 204, "end": 1465 }
internal class ____ { private readonly Assembly _assembly; private IReadOnlyCollection<MigrationDescriptor> _migrations; public MigrationAssembly(Assembly assembly) { _assembly = Guard.NotNull(assembly, nameof(assembly)); } /// <summary> /// Gets all the migrations that are defined in the migrations assembly. /// </summary> public virtual IReadOnlyCollection<MigrationDescriptor> GetMigrations() { IReadOnlyCollection<MigrationDescriptor> Create() { var result = new List<MigrationDescriptor>(); var typeScanner = new DefaultTypeScanner(_assembly); var items = from t in typeScanner.FindTypes<IMigration>() let descriptor = new MigrationDescriptor(t) where descriptor.Version > 0 orderby descriptor.Version select descriptor; foreach (var descriptor in items) { result.Add(descriptor); } return result; } return _migrations ??= Create(); } } }
MigrationAssembly
csharp
npgsql__npgsql
src/Npgsql/Replication/PgOutput/Messages/CommitMessage.cs
{ "start": 161, "end": 1435 }
public sealed class ____ : PgOutputReplicationMessage { /// <summary> /// Flags; currently unused. /// </summary> public CommitFlags Flags { get; private set; } /// <summary> /// The LSN of the commit. /// </summary> public NpgsqlLogSequenceNumber CommitLsn { get; private set; } /// <summary> /// The end LSN of the transaction. /// </summary> public NpgsqlLogSequenceNumber TransactionEndLsn { get; private set; } /// <summary> /// Commit timestamp of the transaction. /// </summary> public DateTime TransactionCommitTimestamp { get; private set; } internal CommitMessage() {} internal CommitMessage Populate(NpgsqlLogSequenceNumber walStart, NpgsqlLogSequenceNumber walEnd, DateTime serverClock, CommitFlags flags, NpgsqlLogSequenceNumber commitLsn, NpgsqlLogSequenceNumber transactionEndLsn, DateTime transactionCommitTimestamp) { base.Populate(walStart, walEnd, serverClock); Flags = flags; CommitLsn = commitLsn; TransactionEndLsn = transactionEndLsn; TransactionCommitTimestamp = transactionCommitTimestamp; return this; } /// <summary> /// Flags for the commit. /// </summary> [Flags]
CommitMessage
csharp
dotnet__tye
samples/dapr/pub-sub/store/OrdersEventBroker.cs
{ "start": 1711, "end": 2063 }
private class ____ { public Entry(string orderId) { OrderId = orderId; Completion = new TaskCompletionSource<OrderConfirmation>(); } public string OrderId { get; } public TaskCompletionSource<OrderConfirmation> Completion { get; } } } }
Entry
csharp
dotnet__efcore
test/EFCore.Specification.Tests/TestModels/ConcurrencyModel/TestDriver.cs
{ "start": 208, "end": 247 }
public class ____ : Driver {
TestDriver
csharp
MassTransit__MassTransit
tests/MassTransit.Tests/SagaStateMachineTests/OutboxFault_Specs.cs
{ "start": 2854, "end": 7205 }
class ____ : MassTransitStateMachine<SomeInstance> { public SomeStateMachine() { InstanceState(x => x.CurrentState); Request(() => HandlerRequest, x => { x.Timeout = TimeSpan.Zero; }); Schedule(() => ScheduleEvent, x => x.TokenId, x => { x.Delay = TimeSpan.FromSeconds(1); x.Received = r => { r.CorrelateById(m => m.Message.CorrelationId); r.ConfigureConsumeTopology = false; }; }); Initially( When(InitialEventReceived) .Then(context => LogContext.Debug?.Log("Initial event, scheduling instance event")) .Schedule(ScheduleEvent, context => new SomeInstanceEvent { CorrelationId = context.Saga.CorrelationId, Count = context.Saga.Count++ }) .TransitionTo(Running)); During(Running, When(ScheduleEvent.Received) .Then(context => LogContext.Debug?.Log("Sending request")) .Schedule(ScheduleEvent, context => new SomeInstanceEvent { CorrelationId = context.Saga.CorrelationId, Count = context.Saga.Count++ }) .Request(HandlerRequest, context => new SomeRequest { Count = context.Saga.Count }) .TransitionTo(Checking) ); During(Checking, When(ScheduleEvent.Received) .Then(context => LogContext.Debug?.Log("Scheduled event received while waiting for request")) .Schedule(ScheduleEvent, context => new SomeInstanceEvent { CorrelationId = context.Saga.CorrelationId, Count = context.Saga.Count++ }) .Request(HandlerRequest, context => new SomeRequest { Count = context.Saga.Count }) .TransitionTo(Suspect) ); During(Suspect, When(ScheduleEvent.Received) .Then(context => LogContext.Debug?.Log("Suspect, scheduled event, faulted time")) .TransitionTo(Failed) .Publish(context => new InstanceCompleted { CorrelationId = context.Saga.CorrelationId, Result = "Faulted" }) ); During(Running, Checking, Suspect, When(HandlerRequest.Completed) .IfElse(context => context.Message.Status == "Running", running => running .Then(context => LogContext.Debug?.Log("Response received, back to running")) .TransitionTo(Running), otherwise => otherwise .Then(context => LogContext.Debug?.Log("Response received, to completed")) .Finalize() ) ); WhenEnter(Final, x => x.Unschedule(ScheduleEvent) .Publish(context => new InstanceCompleted { CorrelationId = context.Saga.CorrelationId, Result = "Success" }) ); } // // ReSharper disable UnassignedGetOnlyAutoProperty public Schedule<SomeInstance, SomeInstanceEvent> ScheduleEvent { get; } public Request<SomeInstance, SomeRequest, SomeResponse> HandlerRequest { get; } public Event<InitialEvent> InitialEventReceived { get; } public State Running { get; } public State Checking { get; } public State Suspect { get; } public State Failed { get; } }
SomeStateMachine
csharp
dotnet__machinelearning
src/Microsoft.ML.AutoML/TrainerExtensions/BinaryTrainerExtensions.cs
{ "start": 547, "end": 2561 }
internal class ____ : ITrainerExtension { private const int DefaultNumIterations = 10; public IEnumerable<SweepableParam> GetHyperparamSweepRanges() { return SweepableParams.BuildAveragePerceptronParams(); } public ITrainerEstimator CreateInstance(MLContext mlContext, IEnumerable<SweepableParam> sweepParams, ColumnInformation columnInfo, IDataView validationSet) { AveragedPerceptronTrainer.Options options = null; if (sweepParams == null || !sweepParams.Any()) { options = new AveragedPerceptronTrainer.Options(); options.NumberOfIterations = DefaultNumIterations; options.LabelColumnName = columnInfo.LabelColumnName; } else { options = TrainerExtensionUtil.CreateOptions<AveragedPerceptronTrainer.Options>(sweepParams, columnInfo.LabelColumnName); if (!sweepParams.Any(p => p.Name == "NumberOfIterations")) { options.NumberOfIterations = DefaultNumIterations; } } return mlContext.BinaryClassification.Trainers.AveragedPerceptron(options); } public PipelineNode CreatePipelineNode(IEnumerable<SweepableParam> sweepParams, ColumnInformation columnInfo) { Dictionary<string, object> additionalProperties = null; if (sweepParams == null || !sweepParams.Any(p => p.Name != "NumberOfIterations")) { additionalProperties = new Dictionary<string, object>() { { "NumberOfIterations", DefaultNumIterations } }; } return TrainerExtensionUtil.BuildPipelineNode(TrainerExtensionCatalog.GetTrainerName(this), sweepParams, columnInfo.LabelColumnName, additionalProperties: additionalProperties); } }
AveragedPerceptronBinaryExtension
csharp
louthy__language-ext
LanguageExt.Core/Immutable Collections/IteratorAsync/IteratorAsync.cs
{ "start": 12328, "end": 14411 }
public sealed class ____ : IteratorAsync<A> { public static readonly IteratorAsync<A> Default = new Nil(); /// <summary> /// Head element /// </summary> public override ValueTask<A> Head => throw new InvalidOperationException("Nil iterator has no head"); /// <summary> /// Tail of the sequence /// </summary> public override ValueTask<IteratorAsync<A>> Tail => new (this); /// <summary> /// Return true if there are no elements in the sequence. /// </summary> public override ValueTask<bool> IsEmpty => new(true); /// <summary> /// Clone the iterator so that we can consume it without having the head item referenced. /// This will stop any GC pressure. /// </summary> public override IteratorAsync<A> Clone() => this; /// <summary> /// When iterating a sequence, it is possible (before evaluation of the `Tail`) to Terminate the current /// iterator and to take a new iterator that continues on from the current location. The reasons for doing /// this are to break the linked-list chain so that there isn't a big linked-list of objects in memory that /// can't be garbage collected. /// </summary> /// <returns>New iterator that starts from the current iterator position</returns> public override IteratorAsync<A> Split() => this; /// <summary> /// Return the number of items in the sequence. /// </summary> /// <remarks> /// Requires all items to be evaluated, this will happen only once however. /// </remarks> [Pure] public override ValueTask<long> Count => new(0); public override ValueTask DisposeAsync() => ValueTask.CompletedTask; } /// <summary> /// Cons iterator case. /// /// Contains a head value and a tail that represents the rest of the sequence. /// </summary>
Nil
csharp
serilog__serilog-sinks-console
test/Serilog.Sinks.Console.Tests/Approval/ApiApprovalTests.cs
{ "start": 122, "end": 825 }
public class ____ { [Fact] public void PublicApi_Should_Not_Change_Unintentionally() { var assembly = typeof(ConsoleLoggerConfigurationExtensions).Assembly; var publicApi = assembly.GeneratePublicApi( new ApiGeneratorOptions() { IncludeAssemblyAttributes = false, ExcludeAttributes = new[] { "System.Diagnostics.DebuggerDisplayAttribute" }, }); publicApi.ShouldMatchApproved(options => options.WithFilenameGenerator((_, __, fileType, fileExtension) => $"{assembly.GetName().Name!}.{fileType}.{fileExtension}")); } } } #endif
ApiApprovalTests
csharp
dotnet__orleans
test/Tester/StreamingTests/StreamingResumeTests.cs
{ "start": 130, "end": 6117 }
public abstract class ____ : TestClusterPerTest { protected static readonly TimeSpan StreamInactivityPeriod = TimeSpan.FromSeconds(5); protected static readonly TimeSpan MetadataMinTimeInCache = StreamInactivityPeriod * 100; protected static readonly TimeSpan DataMaxAgeInCache = StreamInactivityPeriod * 5; protected static readonly TimeSpan DataMinTimeInCache = StreamInactivityPeriod * 4; protected const string StreamProviderName = "StreamingCacheMissTests"; [SkippableFact] public virtual async Task ResumeAfterInactivity() { await ResumeAfterInactivityImpl(false); } [SkippableFact] public virtual async Task ResumeAfterInactivityNotInCache() { await ResumeAfterInactivityImpl(true); } protected virtual async Task ResumeAfterInactivityImpl(bool waitForCacheToFlush) { var streamProvider = this.Client.GetStreamProvider(StreamProviderName); // Tested stream and corresponding grain var key = Guid.NewGuid(); var stream = streamProvider.GetStream<byte[]>(nameof(IImplicitSubscriptionCounterGrain), key); var grain = this.Client.GetGrain<IImplicitSubscriptionCounterGrain>(key); // Data that will be sent to the grains var interestingData = new byte[1] { 1 }; await stream.OnNextAsync(interestingData); await Task.Delay(1_000); // Wait for the stream to become inactive await Task.Delay(StreamInactivityPeriod.Multiply(3)); if (waitForCacheToFlush) { for (var i = 0; i < 5; i++) { var otherStream = streamProvider.GetStream<byte[]>(nameof(IImplicitSubscriptionCounterGrain), Guid.NewGuid()); await otherStream.OnNextAsync(interestingData); } // Wait a bit more for the cache to flush some events await Task.Delay(StreamInactivityPeriod.Multiply(3)); for (var i = 0; i < 5; i++) { var otherStream = streamProvider.GetStream<byte[]>(nameof(IImplicitSubscriptionCounterGrain), Guid.NewGuid()); await otherStream.OnNextAsync(interestingData); } } await stream.OnNextAsync(interestingData); await Task.Delay(2_000); Assert.Equal(0, await grain.GetErrorCounter()); Assert.Equal(2, await grain.GetEventCounter()); } [SkippableFact] public virtual async Task ResumeAfterDeactivation() { var streamProvider = this.Client.GetStreamProvider(StreamProviderName); // Tested stream and corresponding grain var key = Guid.NewGuid(); var stream = streamProvider.GetStream<byte[]>(nameof(IImplicitSubscriptionCounterGrain), key); var grain = this.Client.GetGrain<IImplicitSubscriptionCounterGrain>(key); // Data that will be sent to the grains var interestingData = new byte[1] { 1 }; await stream.OnNextAsync(interestingData); await Task.Delay(1_000); // Wait for the stream to become inactive await Task.Delay(StreamInactivityPeriod.Multiply(3)); await grain.Deactivate(); await stream.OnNextAsync(interestingData); await Task.Delay(2_000); Assert.Equal(0, await grain.GetErrorCounter()); Assert.Equal(2, await grain.GetEventCounter()); } [SkippableFact] public virtual async Task ResumeAfterDeactivationActiveStream() { var streamProvider = this.Client.GetStreamProvider(StreamProviderName); // Tested stream and corresponding grain var key = Guid.NewGuid(); var stream = streamProvider.GetStream<byte[]>(nameof(IImplicitSubscriptionCounterGrain), key); var otherStream = streamProvider.GetStream<byte[]>(nameof(IImplicitSubscriptionCounterGrain), Guid.NewGuid()); var grain = this.Client.GetGrain<IImplicitSubscriptionCounterGrain>(key); await grain.DeactivateOnEvent(true); // Data that will be sent to the grains var interestingData = new byte[1] { 1 }; await stream.OnNextAsync(interestingData); // Push other data await otherStream.OnNextAsync(interestingData); await otherStream.OnNextAsync(interestingData); await otherStream.OnNextAsync(interestingData); await stream.OnNextAsync(interestingData); await Task.Delay(1_000); // Wait for the stream to become inactive await Task.Delay(StreamInactivityPeriod.Multiply(3)); await grain.Deactivate(); await stream.OnNextAsync(interestingData); await Task.Delay(2_000); Assert.Equal(0, await grain.GetErrorCounter()); Assert.Equal(3, await grain.GetEventCounter()); } [SkippableFact] public virtual async Task ResumeAfterSlowSubscriber() { var key = Guid.NewGuid(); var streamProvider = this.Client.GetStreamProvider(StreamProviderName); var stream = streamProvider.GetStream<byte[]>("FastSlowImplicitSubscriptionCounterGrain", key); var fastGrain = this.Client.GetGrain<IFastImplicitSubscriptionCounterGrain>(key); var slowGrain = this.Client.GetGrain<ISlowImplicitSubscriptionCounterGrain>(key); await stream.OnNextAsync([1]); await Task.Delay(500); Assert.Equal(1, await fastGrain.GetEventCounter()); await stream.OnNextAsync([2]); await Task.Delay(500); Assert.Equal(2, await fastGrain.GetEventCounter()); } } }
StreamingResumeTests
csharp
microsoft__semantic-kernel
dotnet/test/VectorData/Qdrant.UnitTests/QdrantCollectionTests.cs
{ "start": 26542, "end": 29150 }
public sealed class ____<T> { [VectorStoreKey] public required T Key { get; set; } [VectorStoreData(IsIndexed = true, IsFullTextIndexed = true)] public string OriginalNameData { get; set; } = string.Empty; [JsonPropertyName("ignored_data_json_name")] [VectorStoreData(IsIndexed = true, StorageName = "data_storage_name")] public string Data { get; set; } = string.Empty; [JsonPropertyName("ignored_vector_json_name")] [VectorStoreVector(4, StorageName = "vector_storage_name")] public ReadOnlyMemory<float>? Vector { get; set; } public string? NotAnnotated { get; set; } } public static IEnumerable<object[]> TestOptions => GenerateAllCombinations(new object[][] { new object[] { true, false }, new object[] { true, false }, new object[] { UlongTestRecordKey1, s_guidTestRecordKey1 } }); public static IEnumerable<object[]> MultiRecordTestOptions => GenerateAllCombinations(new object[][] { new object[] { true, false }, new object[] { true, false }, new object[] { new ulong[] { UlongTestRecordKey1, UlongTestRecordKey2 }, new Guid[] { s_guidTestRecordKey1, s_guidTestRecordKey2 } } }); private static object[][] GenerateAllCombinations(object[][] input) { var counterArray = Enumerable.Range(0, input.Length).Select(x => 0).ToArray(); // Add each item from the first option set as a separate row. object[][] currentCombinations = input[0].Select(x => new object[1] { x }).ToArray(); // Loop through each additional option set. for (int currentOptionSetIndex = 1; currentOptionSetIndex < input.Length; currentOptionSetIndex++) { var iterationCombinations = new List<object[]>(); var currentOptionSet = input[currentOptionSetIndex]; // Loop through each row we have already. foreach (var currentCombination in currentCombinations) { // Add each of the values from the new options set to the current row to generate a new row. for (var currentColumnRow = 0; currentColumnRow < currentOptionSet.Length; currentColumnRow++) { iterationCombinations.Add(currentCombination.Append(currentOptionSet[currentColumnRow]).ToArray()); } } currentCombinations = iterationCombinations.ToArray(); } return currentCombinations; } }
SinglePropsModel
csharp
serilog__serilog-extensions-logging
src/Serilog.Extensions.Logging/Extensions/Logging/LoggerProviderCollectionSink.cs
{ "start": 716, "end": 2536 }
sealed class ____ : ILogEventSink, IDisposable { readonly LoggerProviderCollection _providers; public LoggerProviderCollectionSink(LoggerProviderCollection providers) { _providers = providers ?? throw new ArgumentNullException(nameof(providers)); } public void Emit(LogEvent logEvent) { string categoryName = "None"; EventId eventId = default; if (logEvent.Properties.TryGetValue("SourceContext", out var sourceContextProperty) && sourceContextProperty is ScalarValue sourceContextValue && sourceContextValue.Value is string sourceContext) { categoryName = sourceContext; } if (logEvent.Properties.TryGetValue("EventId", out var eventIdPropertyValue) && eventIdPropertyValue is StructureValue structuredEventId) { string? name = null; var id = 0; foreach (var item in structuredEventId.Properties) { if (item.Name == "Id" && item.Value is ScalarValue sv && sv.Value is int i) id = i; if (item.Name == "Name" && item.Value is ScalarValue sv2 && sv2.Value is string s) name = s; } eventId = new EventId(id, name); } var level = LevelConvert.ToExtensionsLevel(logEvent.Level); var slv = new SerilogLogValues(logEvent.MessageTemplate, logEvent.Properties); foreach (var provider in _providers.Providers) { var logger = provider.CreateLogger(categoryName); logger.Log( level, eventId, slv, logEvent.Exception, (s, e) => s.ToString()); } } public void Dispose() { _providers.Dispose(); } }
LoggerProviderCollectionSink
csharp
ChilliCream__graphql-platform
src/Nitro/CommandLine/src/CommandLine.Cloud/Generated/ApiClient.Client.cs
{ "start": 1807045, "end": 1807370 }
public partial interface ____ : IOnSchemaVersionPublishUpdated_OnSchemaVersionPublishingUpdate_Errors_Changes, IUnionModifiedChange { } [global::System.CodeDom.Compiler.GeneratedCode("StrawberryShake", "15.1.8.0")]
IOnSchemaVersionPublishUpdated_OnSchemaVersionPublishingUpdate_Errors_Changes_UnionModifiedChange
csharp
louthy__language-ext
LanguageExt.Core/Effects/Eff/Eff with runtime/Eff.Module.cs
{ "start": 204, "end": 4538 }
public partial class ____ { /// <summary> /// Construct a successful effect with a pure value /// </summary> /// <param name="value">Pure value to construct the monad with</param> /// <typeparam name="A">Bound value type</typeparam> /// <returns>Synchronous IO monad that captures the pure value</returns> [Pure, MethodImpl(Opt.Default)] public static Eff<RT, A> Success<RT, A>(A value) => Eff<RT, A>.Pure(value); /// <summary> /// Construct a failed effect /// </summary> /// <param name="error">Error that represents the failure</param> /// <typeparam name="A">Bound value type</typeparam> /// <returns>Synchronous IO monad that captures the failure</returns> [Pure, MethodImpl(Opt.Default)] public static Eff<RT, A> Fail<RT, A>(Error error) => Eff<RT, A>.Fail(error); /// <summary> /// Unit effect /// </summary> public static Eff<RT, Unit> unit<RT>() => Success<RT, Unit>(default); //////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Runtime helpers // /// <summary> /// Make the runtime into the bound value /// </summary> [Pure, MethodImpl(Opt.Default)] public static Eff<RT, RT> runtime<RT>() => liftEff<RT, RT>(identity); /// <summary> /// Get all the internal state of the `Eff` /// </summary> [Pure, MethodImpl(Opt.Default)] public static Eff<RT, (RT Runtime, EnvIO EnvIO)> getState<RT>() => new(Eff<RT>.getState); /// <summary> /// Create a new cancellation context and run the provided Aff in that context /// </summary> /// <param name="ma">Operation to run in the next context</param> /// <typeparam name="RT">Runtime environment</typeparam> /// <typeparam name="A">Bound value type</typeparam> /// <returns>An asynchronous effect that captures the operation running in context</returns> public static Eff<RT, A> localCancel<RT, A>(Eff<RT, A> ma) => ma.LocalIO().As(); /// <summary> /// Create a new local context for the environment by mapping the outer environment and then /// using the result as a new context when running the IO monad provided /// </summary> /// <param name="f">Function to map the outer environment into a new one to run `ma`</param> /// <param name="ma">IO monad to run in the new context</param> [Pure, MethodImpl(Opt.Default)] public static Eff<OuterRT, A> local<OuterRT, InnerRT, A>(Func<OuterRT, InnerRT> f, Eff<InnerRT, A> ma) => // Get the current state of the Eff from st in getState<OuterRT>() // Run the local operation from rs in IO.local(ma.effect.Run(f(st.Runtime))).As() // Ignore any changes to the state and just return the result of the local operation select rs; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Lifting // /// <summary> /// Lift an effect into the `Eff` monad /// </summary> [Pure, MethodImpl(Opt.Default)] public static Eff<RT, A> lift<RT, A>(Func<RT, Either<Error, A>> f) => Eff<RT, A>.Lift(f); /// <summary> /// Lift an effect into the `Eff` monad /// </summary> [Pure, MethodImpl(Opt.Default)] public static Eff<RT, A> lift<RT, A>(Func<RT, Fin<A>> f) => Eff<RT, A>.Lift(f); /// <summary> /// Lift an effect into the `Eff` monad /// </summary> [Pure, MethodImpl(Opt.Default)] public static Eff<RT, A> lift<RT, A>(Func<RT, A> f) => Eff<RT, A>.Lift(f); /// <summary> /// Lift an effect into the `Eff` monad /// </summary> [Pure, MethodImpl(Opt.Default)] public static Eff<RT, A> lift<RT, A>(Func<RT, Task<A>> f) => Eff<RT, A>.LiftIO(f); /// <summary> /// Lift an effect into the `Eff` monad /// </summary> [Pure, MethodImpl(Opt.Default)] public static Eff<RT, A> lift<RT, A>(Func<RT, Task<Fin<A>>> f) => Eff<RT, A>.LiftIO(f); /// <summary> /// Lift an effect into the `Eff` monad /// </summary> [Pure, MethodImpl(Opt.Default)] public static Eff<RT, A> lift<RT, A>(IO<A> ma) => Eff<RT, A>.LiftIO(ma); }
Eff
csharp
ServiceStack__ServiceStack
ServiceStack/src/ServiceStack.Common/ActionExecExtensions.cs
{ "start": 249, "end": 3302 }
public static class ____ { public static void ExecAllAndWait(this ICollection<Action> actions, TimeSpan timeout) { var waitHandles = new WaitHandle[actions.Count]; var i = 0; foreach (var action in actions) { waitHandles[i++] = action.BeginInvoke(null, null).AsyncWaitHandle; } WaitAll(waitHandles, timeout); } public static List<WaitHandle> ExecAsync(this IEnumerable<Action> actions) { var waitHandles = new List<WaitHandle>(); foreach (var action in actions) { var waitHandle = new AutoResetEvent(false); waitHandles.Add(waitHandle); var commandExecsHandler = new ActionExecHandler(action, waitHandle); #if NETCORE Task.Run(() => commandExecsHandler.Execute()); #elif NETFX_CORE ThreadPool.RunAsync(new WorkItemHandler((IAsyncAction) => commandExecsHandler.Execute())); #else ThreadPool.QueueUserWorkItem(x => ((ActionExecHandler)x).Execute(), commandExecsHandler); #endif } return waitHandles; } public static bool WaitAll(this List<WaitHandle> waitHandles, int timeoutMs) { return WaitAll(waitHandles.ToArray(), timeoutMs); } public static bool WaitAll(this ICollection<WaitHandle> waitHandles, int timeoutMs) { return WaitAll(waitHandles.ToArray(), timeoutMs); } public static bool WaitAll(this ICollection<WaitHandle> waitHandles, TimeSpan timeout) { return WaitAll(waitHandles.ToArray(), (int)timeout.TotalMilliseconds); } #if !SL5 && !IOS && !XBOX public static bool WaitAll(this List<IAsyncResult> asyncResults, TimeSpan timeout) { var waitHandles = asyncResults.ConvertAll(x => x.AsyncWaitHandle); return WaitAll(waitHandles.ToArray(), (int)timeout.TotalMilliseconds); } public static bool WaitAll(WaitHandle[] waitHandles, TimeSpan timeout) { return WaitAll(waitHandles, (int)timeout.TotalMilliseconds); } public static bool WaitAll(WaitHandle[] waitHandles, int timeOutMs) { // throws an exception if there are no wait handles if (waitHandles == null) throw new ArgumentNullException(nameof(waitHandles)); if (waitHandles.Length == 0) return true; #if NETCORE return WaitHandle.WaitAll(waitHandles, timeOutMs); #else if (Thread.CurrentThread.GetApartmentState() == ApartmentState.STA) { // WaitAll for multiple handles on an STA thread is not supported. // CurrentThread is ApartmentState.STA when run under unit tests var successfullyComplete = true; foreach (var waitHandle in waitHandles) { successfullyComplete = successfullyComplete && waitHandle.WaitOne(timeOutMs, false); } return successfullyComplete; } return WaitHandle.WaitAll(waitHandles, timeOutMs, false); #endif } #endif }
ActionExecExtensions
csharp
MassTransit__MassTransit
src/MassTransit/Internals/Caching/ITimeToLiveCacheValue.cs
{ "start": 46, "end": 198 }
public interface ____<TValue> : ICacheValue<TValue> where TValue : class { long Timestamp { get; } } }
ITimeToLiveCacheValue
csharp
ChilliCream__graphql-platform
src/HotChocolate/Core/test/Types.Tests/Configuration/SchemaTypeDiscoveryTests.cs
{ "start": 3460, "end": 3637 }
public class ____(Bar bar) { public Bar Bar { get; } = bar; public Foo GetFoo(Foo foo) { return foo; } }
QueryFieldArgument
csharp
dotnet__efcore
test/EFCore.Design.Tests/Migrations/Design/CSharpMigrationsGeneratorTest.ModelSnapshot.cs
{ "start": 18342, "end": 18495 }
private class ____ : BaseEntityWithStructDiscriminator { public string Title { get; set; } }
AnotherDerivedEntityWithStructDiscriminator
csharp
Cysharp__ZLogger
src/ZLogger.Unity/Assets/ZLogger.Unity/Runtime/ZLoggerUnityDebugLoggerProvider.cs
{ "start": 346, "end": 484 }
public sealed class ____ : ZLoggerOptions { public bool PrettyStacktrace { get; set; } = true; }
ZLoggerUnityDebugOptions
csharp
JamesNK__Newtonsoft.Json
Src/Newtonsoft.Json.Tests/Documentation/TraceWriterTests.cs
{ "start": 2448, "end": 2624 }
public static class ____ { public static Logger GetLogger(string className) { return new Logger(); } } [TestFixture]
LogManager
csharp
dotnet__BenchmarkDotNet
tests/BenchmarkDotNet.Tests/Running/JobRuntimePropertiesComparerTests.cs
{ "start": 1418, "end": 2317 }
public class ____ { [Benchmark] public void M1() { } [Benchmark] public void M2() { } [Benchmark] public void M3() { } } [Fact] public void BenchmarksAreGroupedByJob() { var benchmarks = BenchmarkConverter.TypeToBenchmarks(typeof(AllRuntimes)); var grouped = benchmarks.BenchmarksCases .GroupBy(benchmark => benchmark, new BenchmarkPartitioner.BenchmarkRuntimePropertiesComparer()) .ToArray(); Assert.Equal(3, grouped.Length); // Clr + Mono + Core foreach (var grouping in grouped) Assert.Equal(2, grouping.Count()); // M1 + M2 } [SimpleJob(runtimeMoniker: RuntimeMoniker.Net462)] [SimpleJob(runtimeMoniker: RuntimeMoniker.Mono)] [SimpleJob(runtimeMoniker: RuntimeMoniker.Net50)]
Plain3
csharp
dotnet__orleans
src/api/Orleans.Serialization/Orleans.Serialization.cs
{ "start": 135603, "end": 136454 }
partial class ____<T1, T2, T3, T4, T5, T6, T7, T8> : IFieldCodec<System.Tuple<T1, T2, T3, T4, T5, T6, T7, T8>>, IFieldCodec { public TupleCodec(IFieldCodec<T1> item1Codec, IFieldCodec<T2> item2Codec, IFieldCodec<T3> item3Codec, IFieldCodec<T4> item4Codec, IFieldCodec<T5> item5Codec, IFieldCodec<T6> item6Codec, IFieldCodec<T7> item7Codec, IFieldCodec<T8> item8Codec) { } public System.Tuple<T1, T2, T3, T4, T5, T6, T7, T8> ReadValue<TInput>(ref Buffers.Reader<TInput> reader, WireProtocol.Field field) { throw null; } public void WriteField<TBufferWriter>(ref Buffers.Writer<TBufferWriter> writer, uint fieldIdDelta, System.Type expectedType, System.Tuple<T1, T2, T3, T4, T5, T6, T7, T8> value) where TBufferWriter : System.Buffers.IBufferWriter<byte> { } } [RegisterCopier] public sealed
TupleCodec
csharp
dotnet__maui
src/Controls/tests/TestCases.Shared.Tests/Tests/Issues/Issue11769.cs
{ "start": 517, "end": 918 }
public class ____ : _IssuesUITest { public Issue11769_DelayedShellSection(TestDevice testDevice) : base(testDevice) { } public override string Issue => "[Bug] Shell throws exception when delay adding Shell Section"; [Test] [Category(UITestCategories.Shell)] public void DelayedAddingOfShellSectionDoesntCrash() { App.WaitForElement("Success"); } }
Issue11769_DelayedShellSection
csharp
exceptionless__Exceptionless
src/Exceptionless.Core/Models/StackSummaryModel.cs
{ "start": 180, "end": 545 }
public record ____ : SummaryData { public required string Title { get; init; } public StackStatus Status { get; init; } public DateTime FirstOccurrence { get; init; } public DateTime LastOccurrence { get; init; } public long Total { get; init; } public double Users { get; init; } public double TotalUsers { get; init; } }
StackSummaryModel
csharp
dotnet__orleans
test/Orleans.Serialization.UnitTests/BuiltInCodecTests.cs
{ "start": 93228, "end": 93687 }
public class ____ : List<int> { public TypeWithListBase() : this(true) { } public TypeWithListBase(bool addDefaultValue) { if (addDefaultValue) { this.Add(42); } } [Id(0)] public int OtherProperty { get; set; } public override string ToString() => $"[OtherProperty: {OtherProperty}, Values: [{string.Join(", ", this)}]]"; }
TypeWithListBase
csharp
EventStore__EventStore
src/KurrentDB.Common/Configuration/MetricsConfiguration.cs
{ "start": 1421, "end": 1577 }
public enum ____ { Cpu = 1, LoadAverage1m, LoadAverage5m, LoadAverage15m, FreeMem, TotalMem, DriveTotalBytes, DriveUsedBytes, }
SystemTracker
csharp
MonoGame__MonoGame
MonoGame.Framework/Platform/Native/RenderTarget3D.Native.cs
{ "start": 246, "end": 815 }
public partial class ____ { private unsafe void PlatformConstruct(GraphicsDevice graphicsDevice, int width, int height, bool mipMap, DepthFormat preferredDepthFormat, int preferredMultiSampleCount, RenderTargetUsage usage) { Handle = MGG.RenderTarget_Create( GraphicsDevice.Handle, TextureType._3D, _format, width, height, Depth, _levelCount, 1, preferredDepthFormat, preferredMultiSampleCount, usage); } }
RenderTarget3D
csharp
ChilliCream__graphql-platform
src/Nitro/CommandLine/src/CommandLine.Cloud/Generated/ApiClient.Client.cs
{ "start": 2119685, "end": 2122416 }
public partial class ____ : global::System.IEquatable<OnSchemaVersionValidationUpdated_OnSchemaVersionValidationUpdate_Errors_Changes_Changes_EnumValueRemoved>, IOnSchemaVersionValidationUpdated_OnSchemaVersionValidationUpdate_Errors_Changes_Changes_EnumValueRemoved { public OnSchemaVersionValidationUpdated_OnSchemaVersionValidationUpdate_Errors_Changes_Changes_EnumValueRemoved(global::System.String __typename, global::ChilliCream.Nitro.CommandLine.Cloud.Client.SchemaChangeSeverity severity, global::System.String coordinate) { this.__typename = __typename; Severity = severity; Coordinate = coordinate; } /// <summary> /// The name of the current Object type at runtime. /// </summary> public global::System.String __typename { get; } public global::ChilliCream.Nitro.CommandLine.Cloud.Client.SchemaChangeSeverity Severity { get; } public global::System.String Coordinate { get; } public virtual global::System.Boolean Equals(OnSchemaVersionValidationUpdated_OnSchemaVersionValidationUpdate_Errors_Changes_Changes_EnumValueRemoved? other) { if (ReferenceEquals(null, other)) { return false; } if (ReferenceEquals(this, other)) { return true; } if (other.GetType() != GetType()) { return false; } return (__typename.Equals(other.__typename)) && Severity.Equals(other.Severity) && Coordinate.Equals(other.Coordinate); } public override global::System.Boolean Equals(global::System.Object? obj) { if (ReferenceEquals(null, obj)) { return false; } if (ReferenceEquals(this, obj)) { return true; } if (obj.GetType() != GetType()) { return false; } return Equals((OnSchemaVersionValidationUpdated_OnSchemaVersionValidationUpdate_Errors_Changes_Changes_EnumValueRemoved)obj); } public override global::System.Int32 GetHashCode() { unchecked { int hash = 5; hash ^= 397 * __typename.GetHashCode(); hash ^= 397 * Severity.GetHashCode(); hash ^= 397 * Coordinate.GetHashCode(); return hash; } } } [global::System.CodeDom.Compiler.GeneratedCode("StrawberryShake", "15.1.8.0")]
OnSchemaVersionValidationUpdated_OnSchemaVersionValidationUpdate_Errors_Changes_Changes_EnumValueRemoved
csharp
abpframework__abp
modules/docs/src/Volo.Docs.Domain/Volo/Docs/Projects/IProjectRepository.cs
{ "start": 174, "end": 759 }
public interface ____ : IBasicRepository<Project, Guid> { Task<List<Project>> GetListAsync(string sorting, int maxResultCount, int skipCount,bool includeDetails = false, CancellationToken cancellationToken = default); Task<List<ProjectWithoutDetails>> GetListWithoutDetailsAsync(CancellationToken cancellationToken = default); Task<Project> GetByShortNameAsync(string shortName, CancellationToken cancellationToken = default); Task<bool> ShortNameExistsAsync(string shortName, CancellationToken cancellationToken = default); } }
IProjectRepository
csharp
ardalis__GuardClauses
test/GuardClauses.UnitTests/GuardAgainstOutOfRangeForEnumerableShort.cs
{ "start": 5071, "end": 5544 }
public class ____ : IEnumerable<object[]> { public IEnumerator<object[]> GetEnumerator() { yield return new object[] { new List<short> { 10, 12, 15 }, 10, 12 }; yield return new object[] { new List<short> { 100, 200, 120, 180 }, 100, 150 }; yield return new object[] { new List<short> { 15, 120, 158 }, 10, 110 }; } IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); }
IncorrectClassData
csharp
CommunityToolkit__dotnet
tests/CommunityToolkit.Mvvm.SourceGenerators.UnitTests/Test_SourceGeneratorsCodegen.cs
{ "start": 95482, "end": 96152 }
partial class ____ { [RelayCommand] [field: Value(0)] [property: Value(1)] private partial void Test1() { } [field: Value(2)] [property: Value(3)] private partial void Test1(); [field: Value(0)] [property: Value(1)] private partial void Test2() { } [RelayCommand] [field: Value(2)] [property: Value(3)] private partial void Test2(); }
MyViewModel
csharp
mongodb__mongo-csharp-driver
tests/MongoDB.Bson.Tests/PowerOf2Tests.cs
{ "start": 817, "end": 2860 }
public class ____ { [Theory] [ParameterAttributeData] public void IsPowerOf2_should_return_false_when_not_a_power_of_2( [Values(3, 5, 6, 7, 9, 127, 129, 0x37ffffff)] int n) { var result = PowerOf2.IsPowerOf2(n); result.Should().BeFalse(); } [Theory] [ParameterAttributeData] public void IsPowerOf2_should_return_true_when_a_power_of_2( [Values(0, 1, 2, 4, 8, 128, 0x40000000)] int n) { var result = PowerOf2.IsPowerOf2(n); result.Should().BeTrue(); } [Theory] [ParameterAttributeData] public void IsPowerOf2_should_throw_when_n_is_invalid( [Values(-1, 0x40000001)] int n) { Action action = () => PowerOf2.IsPowerOf2(n); action.ShouldThrow<ArgumentOutOfRangeException>().And.ParamName.Should().Be("n"); } [Theory] [InlineData(0, 0)] [InlineData(1, 1)] [InlineData(2, 2)] [InlineData(3, 4)] [InlineData(4, 4)] [InlineData(5, 8)] [InlineData(6, 8)] [InlineData(7, 8)] [InlineData(8, 8)] [InlineData(9, 16)] [InlineData(127, 128)] [InlineData(128, 128)] [InlineData(129, 256)] [InlineData(0x37ffffff, 0x40000000)] [InlineData(0x40000000, 0x40000000)] public void RoundUpToPowerOf2_should_return_expected_result(int n, int expectedResult) { var result = PowerOf2.RoundUpToPowerOf2(n); result.Should().Be(expectedResult); } [Theory] [ParameterAttributeData] public void RoundUpToPowerOf2_should_throw_when_n_is_invalid( [Values(-1, 0x40000001)] int n) { Action action = () => PowerOf2.RoundUpToPowerOf2(n); action.ShouldThrow<ArgumentOutOfRangeException>().And.ParamName.Should().Be("n"); } } }
PowerOf2Tests
csharp
npgsql__npgsql
src/Npgsql/ICancelable.cs
{ "start": 65, "end": 166 }
interface ____ : IDisposable, IAsyncDisposable { void Cancel(); Task CancelAsync(); }
ICancelable
csharp
mongodb__mongo-csharp-driver
src/MongoDB.Bson/Serialization/Conventions/HierarchicalDiscriminatorConvention.cs
{ "start": 869, "end": 924 }
class ____ to the actual type. /// </summary>
down
csharp
ChilliCream__graphql-platform
src/HotChocolate/Raven/src/Data/Pagination/RavenPaginationRequestExecutorBuilderExtensions.cs
{ "start": 280, "end": 1456 }
public static class ____ { /// <summary> /// Adds the Raven cursor and offset paging providers. /// </summary> /// <param name="builder"> /// The GraphQL configuration builder. /// </param> /// <param name="providerName"> /// The name which shall be used to refer to this registration. /// </param> /// <param name="defaultProvider"> /// Defines if these providers shall be registered as default providers. /// </param> /// <returns> /// Returns the GraphQL configuration builder for further configuration chaining. /// </returns> public static IRequestExecutorBuilder AddRavenPagingProviders( this IRequestExecutorBuilder builder, string providerName = RavenPagination.ProviderName, bool defaultProvider = false) { ArgumentNullException.ThrowIfNull(builder); builder.RegisterDocumentStore(); builder.AddCursorPagingProvider<RavenCursorPagingProvider>(providerName, defaultProvider); builder.AddOffsetPagingProvider<RavenOffsetPagingProvider>(providerName, defaultProvider); return builder; } }
RavenPaginationRequestExecutorBuilderExtensions
csharp
dotnet__machinelearning
src/Microsoft.ML.FastTree/Dataset/DenseIntArray.cs
{ "start": 6028, "end": 7268 }
class ____ a byte buffer, at a given position. /// The position is incremented to the end of the representation /// </summary> /// <param name="buffer">a byte array where the binary representation is written</param> /// <param name="position">the position in the byte array</param> public override void ToByteArray(byte[] buffer, ref int position) { base.ToByteArray(buffer, ref position); Length.ToByteArray(buffer, ref position); } public override int this[int index] { get { Contracts.Assert(0 <= index && index < Length); return 0; } set { Contracts.Assert(0 <= index && index < Length); Contracts.Assert(value == 0); } } public override void Sumup(SumupInputData input, FeatureHistogram histogram) { histogram.SumTargetsByBin[0] = input.SumTargets; if (histogram.SumWeightsByBin != null) histogram.SumWeightsByBin[0] = input.SumWeights; histogram.CountByBin[0] = input.TotalCount; } } /// <summary> /// A
to
csharp
bitwarden__server
test/Infrastructure.EFIntegration.Test/Helpers/DatabaseOptionsFactory.cs
{ "start": 336, "end": 3152 }
public static class ____ { public static List<DbContextOptions<DatabaseContext>> Options { get; } = new(); static DatabaseOptionsFactory() { var services = new ServiceCollection() .AddSingleton(sp => { var dataProtector = Substitute.For<IDataProtector>(); dataProtector.Unprotect(Arg.Any<byte[]>()) .Returns<byte[]>(data => Encoding.UTF8.GetBytes(Constants.DatabaseFieldProtectedPrefix + Encoding.UTF8.GetString((byte[])data[0]))); var dataProtectionProvider = Substitute.For<IDataProtectionProvider>(); dataProtectionProvider.CreateProtector(Constants.DatabaseFieldProtectorPurpose) .Returns(dataProtector); return dataProtectionProvider; }) .BuildServiceProvider(); var globalSettings = GlobalSettingsFactory.GlobalSettings; if (!string.IsNullOrWhiteSpace(GlobalSettingsFactory.GlobalSettings.PostgreSql?.ConnectionString)) { AppContext.SetSwitch("Npgsql.EnableLegacyTimestampBehavior", true); Options.Add(new DbContextOptionsBuilder<DatabaseContext>() .UseNpgsql(globalSettings.PostgreSql.ConnectionString, npgsqlDbContextOptionsBuilder => { npgsqlDbContextOptionsBuilder.MigrationsAssembly(nameof(PostgresMigrations)); }) .UseApplicationServiceProvider(services) .Options); } if (!string.IsNullOrWhiteSpace(GlobalSettingsFactory.GlobalSettings.MySql?.ConnectionString)) { var mySqlConnectionString = globalSettings.MySql.ConnectionString; Options.Add(new DbContextOptionsBuilder<DatabaseContext>() .UseMySql(mySqlConnectionString, ServerVersion.AutoDetect(mySqlConnectionString), mySqlDbContextOptionsBuilder => { mySqlDbContextOptionsBuilder.MigrationsAssembly(nameof(MySqlMigrations)); }) .UseApplicationServiceProvider(services) .Options); } if (!string.IsNullOrWhiteSpace(GlobalSettingsFactory.GlobalSettings.Sqlite?.ConnectionString)) { var sqliteConnectionString = globalSettings.Sqlite.ConnectionString; Options.Add(new DbContextOptionsBuilder<DatabaseContext>() .UseSqlite(sqliteConnectionString, mySqlDbContextOptionsBuilder => { mySqlDbContextOptionsBuilder.MigrationsAssembly(nameof(SqliteMigrations)); }) .UseApplicationServiceProvider(services) .Options); } } }
DatabaseOptionsFactory
csharp
exceptionless__Exceptionless
src/Exceptionless.Core/Pipeline/Base/PipelineContextBase.cs
{ "start": 1661, "end": 3340 }
public abstract class ____ : IPipelineContext { /// <summary> /// Gets or sets a value indicating whether this pipeline is cancelled. /// </summary> /// <value> /// <c>true</c> if this pipeline is cancelled; otherwise, <c>false</c>. /// </value> public bool IsCancelled { get; set; } /// <summary> /// Gets or sets a value indicating whether this pipeline context is processed. /// </summary> /// <value> /// <c>true</c> if this pipeline context is processed; otherwise, <c>false</c>. /// </value> public bool IsProcessed { get; set; } /// <summary> /// Gets a value indicating whether or not this context has gotten an error during processing. /// </summary> public bool HasError => ErrorMessage is not null || Exception is not null; /// <summary> /// Used to set the context into an errored state with an error message and possibly exception with details. /// </summary> /// <param name="message">The error message.</param> /// <param name="ex">The Exception that occurred.</param> public void SetError(string message, Exception? ex = null) { ErrorMessage = message; Exception = ex; } /// <summary> /// The error message that occurred during processing. /// </summary> public string? ErrorMessage { get; private set; } /// <summary> /// Gets or sets the exception that occurred during processing of this context. /// </summary> /// <value> /// <c>Exception</c> if an error occurred during processing; otherwise, <c>null</c>. /// </value> public Exception? Exception { get; private set; } }
PipelineContextBase