C# 添加到实体中的集合

C# 添加到实体中的集合,c#,entity-framework-core,C#,Entity Framework Core,我有一个班级学校,可以举办很多活动 public class School: Entity<Guid> { public string Name { get; set; } public ICollection<Event> Events { get; set; } = new List<Event>(); public void AddEvent(Event newEvent) { Events.Add(ne

我有一个班级学校,可以举办很多活动

public class School: Entity<Guid>
{
    public string Name { get; set; }
    public ICollection<Event> Events { get; set; } = new List<Event>();
    public void AddEvent(Event newEvent) 
    {
        Events.Add(newEvent);
    }
}
公立学校:实体
{
公共字符串名称{get;set;}
公共ICollection事件{get;set;}=new List();
公共无效添加事件(事件newEvent)
{
Events.Add(newEvent);
}
}
这是事件类

public class Event : Entity<Guid>
{
    public string Title { get; set; }
    public string Description { get; set; }
    public DateTime EventStart { get; set; }
}
公共类事件:实体
{
公共字符串标题{get;set;}
公共字符串说明{get;set;}
公共日期时间事件开始{get;set;}
}
这是一个实体类-不相关,但如果有人想看到

public abstract class Entity<TId> 
{
    public TId Id { get; set; }
}
公共抽象类实体
{
公共TId Id{get;set;}
}
当我想为学校添加一个新事件时,我用事件类的属性调用一个POST端点

[HttpPost]
public async Task<IActionResult> CreateEvent(Guid schoolId, Event newEvent)
{
     var school = await _context.School.FirstOrDefaultAsync(x => x.Id == schoolId);
     
     school.AddEvent(newEvent);
     
     await _context.SaveChangesAsync();
     
     return Ok();
}
[HttpPost]
公共异步任务CreateEvent(Guid schoolId,Event newEvent)
{
var school=wait_context.school.FirstOrDefaultAsync(x=>x.Id==schoolId);
学校。附加事件(新事件);
wait_context.SaveChangesAsync();
返回Ok();
}
但是,由于某些原因,这会导致此错误

完整堆栈跟踪

System.ArgumentNullException: Value cannot be null. (Parameter 'key')
   at System.Collections.Generic.Dictionary`2.FindEntry(TKey key)
   at System.Collections.Generic.Dictionary`2.TryGetValue(TKey key, TValue& value)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.EntityReferenceMap.TryGet(Object entity, IEntityType entityType, InternalEntityEntry& entry, Boolean throwOnNonUniqueness)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.TryGetEntry(Object entity, IEntityType entityType, Boolean throwOnTypeMismatch)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.NavigationFixer.InitialFixup(InternalEntityEntry entry, Boolean fromQuery)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.NavigationFixer.StateChanged(InternalEntityEntry entry, EntityState oldState, Boolean fromQuery)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.InternalEntityEntryNotifier.StateChanged(InternalEntityEntry entry, EntityState oldState, Boolean fromQuery)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.InternalEntityEntry.FireStateChanged(EntityState oldState)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.InternalEntityEntry.SetEntityState(EntityState oldState, EntityState newState, Boolean acceptChanges, Boolean modifyProperties)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.InternalEntityEntry.SetEntityState(EntityState entityState, Boolean acceptChanges, Boolean modifyProperties, Nullable`1 forceStateWhenUnknownKey)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.EntityGraphAttacher.PaintAction(EntityEntryGraphNode`1 node)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.EntityEntryGraphIterator.TraverseGraph[TState](EntityEntryGraphNode`1 node, Func`2 handleNode)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.EntityEntryGraphIterator.TraverseGraph[TState](EntityEntryGraphNode`1 node, Func`2 handleNode)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.EntityEntryGraphIterator.TraverseGraph[TState](EntityEntryGraphNode`1 node, Func`2 handleNode)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.EntityGraphAttacher.AttachGraph(InternalEntityEntry rootEntry, EntityState targetState, EntityState storeGeneratedWithKeySetTargetState, Boolean forceStateWhenUnknownKey)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.NavigationFixer.NavigationCollectionChanged(InternalEntityEntry entry, INavigationBase navigationBase, IEnumerable`1 added, IEnumerable`1 removed)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.InternalEntityEntryNotifier.NavigationCollectionChanged(InternalEntityEntry entry, INavigationBase navigationBase, IEnumerable`1 added, IEnumerable`1 removed)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.ChangeDetector.DetectNavigationChange(InternalEntityEntry entry, INavigationBase navigationBase)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.ChangeDetector.LocalDetectChanges(InternalEntityEntry entry)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.ChangeDetector.DetectChanges(IStateManager stateManager)
   at Microsoft.EntityFrameworkCore.ChangeTracking.ChangeTracker.DetectChanges()
   at Microsoft.EntityFrameworkCore.DbContext.TryDetectChanges()
   at Microsoft.EntityFrameworkCore.DbContext.SaveChangesAsync(Boolean acceptAllChangesOnSuccess, CancellationToken cancellationToken)
   at MakersOfDenmark.WebAPI.Controllers.EventController.CreateEvent(Guid schoolId, Event newEvent) in C:\Users\mathi\Source\Repos\makersofdenmark\src\MakersOfDenmark.WebAPI\Controllers\EventController.cs:line 50
   at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.TaskOfIActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeActionMethodAsync>g__Logged|12_1(ControllerActionInvoker invoker)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeNextActionFilterAsync>g__Awaited|10_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeInnerFilterAsync>g__Awaited|13_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Logged|17_1(ResourceInvoker invoker)
   at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
   at Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext httpContext)
   at Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext, ISwaggerProvider swaggerProvider)
   at Serilog.AspNetCore.RequestLoggingMiddleware.Invoke(HttpContext httpContext)
   at Elmah.Io.AspNetCore.Serilog.ElmahIoSerilogMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
System.ArgumentNullException:值不能为null。(参数“key”)
at System.Collections.Generic.Dictionary`2.FindEntry(TKey)
在System.Collections.Generic.Dictionary`2.TryGetValue(TKey、TValue和value)
位于Microsoft.EntityFrameworkCore.ChangeTracking.Internal.EntityReferenceMap.TryGet(对象实体、entityType entityType、InternalEntityEntry和entry、布尔Throwon非唯一性)
位于Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.TryGetEntry(对象实体,IEntityType entityType,布尔throwOnTypeMismatch)
位于Microsoft.EntityFrameworkCore.ChangeTracking.Internal.NavigationFixer.InitialFixup(InternalEntityEntry条目,布尔fromQuery)
位于Microsoft.EntityFrameworkCore.ChangeTracking.Internal.NavigationFixer.StateChanged(InternalEntityEntry条目、EntityState oldState、布尔fromQuery)
位于Microsoft.EntityFrameworkCore.ChangeTracking.Internal.InternalEntityEntryNotifier.StateChanged(InternalEntityEntry条目、EntityState oldState、布尔fromQuery)
位于Microsoft.EntityFrameworkCore.ChangeTracking.Internal.InternalEntityEntry.FireStateChanged(EntityState oldState)
位于Microsoft.EntityFrameworkCore.ChangeTracking.Internal.InternalEntityEntry.SetEntityState(EntityState oldState、EntityState newState、Boolean acceptChanges、Boolean modifyProperties)
位于Microsoft.EntityFrameworkCore.ChangeTracking.Internal.InternalEntityEntry.SetEntityState(EntityState EntityState、Boolean acceptChanges、Boolean modifyProperties、Nullable`1 forceStateWhenUnknownKey)
位于Microsoft.EntityFrameworkCore.ChangeTracking.Internal.EntityGraphAttacher.PaintAction(EntityEntryGraphNode`1节点)
位于Microsoft.EntityFrameworkCore.ChangeTracking.Internal.EntityEntryGraphIterator.TraverseGraph[TSState](EntityEntryGraphNode`1节点,Func`2 handleNode)
位于Microsoft.EntityFrameworkCore.ChangeTracking.Internal.EntityEntryGraphIterator.TraverseGraph[TSState](EntityEntryGraphNode`1节点,Func`2 handleNode)
位于Microsoft.EntityFrameworkCore.ChangeTracking.Internal.EntityEntryGraphIterator.TraverseGraph[TSState](EntityEntryGraphNode`1节点,Func`2 handleNode)
在Microsoft.EntityFrameworkCore.ChangeTracking.Internal.EntityGraphAttacher.AttachGraph(InternalEntityEntry rootEntry、EntityState targetState、EntityState StoreWithKeySetTargetState生成的EntityState、Boolean ForceState WhenUnknownkey)
在Microsoft.EntityFrameworkCore.ChangeTracking.Internal.NavigationFixer.NavigationCollectionChanged(InternalEntityEntry条目,INavigationBase navigationBase,添加了IEnumerable`1,删除了IEnumerable`1)
在Microsoft.EntityFrameworkCore.ChangeTracking.Internal.InternalEntityEntryNotifier.NavigationCollectionChanged(InternalEntityEntry条目,INavigationBase导航库,添加了IEnumerable`1,删除了IEnumerable`1)
位于Microsoft.EntityFrameworkCore.ChangeTracking.Internal.ChangeDetector.DetectNavigationChange(InternalEntityEntry条目,INavigationBase navigationBase)
位于Microsoft.EntityFrameworkCore.ChangeTracking.Internal.ChangeDetector.LocalDetectChanges(InternalEntityEntry条目)
位于Microsoft.EntityFrameworkCore.ChangeTracking.Internal.ChangeDetector.DetectChanges(IStateManager stateManager)
在Microsoft.EntityFrameworkCore.ChangeTracking.ChangeTracker.DetectChanges()中
在Microsoft.EntityFrameworkCore.DbContext.TryDetectChanges()中
在Microsoft.EntityFrameworkCore.DbContext.SaveChangesSync(布尔值AcceptillChangesOnSuccess,CancellationToken CancellationToken)
在C:\Users\mathi\Source\Repos\MakersOfDenmark\src\MakersOfDenmark.WebAPI\Controllers\eventcontrollers\EventController.CreateEvent(Guid学校ID,Event newEvent)中的MakersOfDenmark.WebAPI
位于Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.TaskOfActionResultExecutor.Execute(IActionResultTypeMapper映射器、ObjectMethodExecutor执行器、对象控制器、对象[]参数)
在Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.g|u记录| 12_1(ControllerActionInvoker invoker invoker)
在Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.g_u等待| 10_0(ControllerActionInvoker invoker,Task lastTask,State next,Scope Scope,Object State,Boolean isCompleted)
位于Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed上下文)
位于Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(状态和下一步、范围和范围、对象和状态、布尔值和isCompleted)
在Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.g_u等待| 13_0(ControllerActionInvoker invoker,Task lastTask,State next,Scope Scope,Object State,Boolean isCompleted)
在Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g_|19_0(ResourceInvoker invoker、Task lastTask、State next、Scope Scope、Object State、Boolean isCompleted)
public class School: Entity<Guid>
{
    public string Name { get; set; }
    public ICollection<Event> Events { get; set; } = new List<Event>();

    public void AddEvent(Event newEvent) 
    {
        Events.Add(newEvent);
    }
}

public class Event : Entity<Guid>
{
    public string Title { get; set; }
    public string Description { get; set; }
    public DateTime EventStart { get; set; }
    public School School { get;set; }
    public Guid SchoolId { get;set; }
}


//on your DB context
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Event>().HasOne(x => x.School).WithMany(x => x.Events);
}