【问题标题】:Error when trying to create many to many relationship in asp.net尝试在 asp.net 中创建多对多关系时出错
【发布时间】:2015-11-22 14:05:58
【问题描述】:

我在尝试创建多对多关系模型时遇到了 Asp.Net 问题,尝试注册帐户时出现此错误:

序列不包含匹配元素

当我“禁用”我的更改时,我可以正常在网站上注册,因此我的模型中存在一些关于列结构的错误,但我无法自己修复它们。我想在BookmarkTag 表之间创建多对多连接,并且多对多表应具有以下结构:IdBookmarkIDTagID

这是我的模型:

public class Bookmark
{   
    [Key]
    public int BookmarkID { get; set; }

    public string Url { get; set; }

    public ApplicationUser UserId { get; set; }

    public virtual ICollection<BookmarkTag> BookmarkTags { get; set; }
}

public class Tag
{
    [Key]
    public int TagID { get; set; }

    [Column(TypeName="varchar(60)")]
    public string TagName { get; set; }

    public virtual ICollection<BookmarkTag> BookmarkTags { get; set; }
}

public class BookmarkTag
{
    [Key, Column(Order = 0)]
    public int BookmarkTagID { get; set; }

    [Key, Column(Order = 1)]
    public int BookmarkID { get; set; }

    [Key, Column(Order = 2)]
    public int TagID { get; set; }

    public virtual Bookmark Bookmark { get; set; }
    public virtual Tag Tag { get;  set;}
}

这里也是错误堆栈跟踪:

[InvalidOperationException:序列不包含匹配元素]
System.Linq.Enumerable.Single(IEnumerable1 source, Func2 谓词) +2603017 System.Data.Entity.Utilities.DbProviderManifestExtensions.GetStoreTypeFromName(DbProviderManifest providerManifest,字符串名称)+81
System.Data.Entity.ModelConfiguration.Configuration.Properties.Primitive.PrimitivePropertyConfiguration.ConfigureColumn(EdmProperty 列、EntityType 表、DbProviderManifest providerManifest) +87
System.Data.Entity.ModelConfiguration.Configuration.Properties.Primitive.PrimitivePropertyConfiguration.Configure(EdmProperty 列、EntityType 表、DbProviderManifest providerManifest、Boolean allowOverride,布尔型 fillFromExistingConfiguration) +138
System.Data.Entity.ModelConfiguration.Configuration.Properties.Primitive.c__DisplayClass4.b__3(Tuple2 pm) +38
System.Data.Entity.Utilities.IEnumerableExtensions.Each(IEnumerable
1 ts, 行动1 action) +130
System.Data.Entity.ModelConfiguration.Configuration.Properties.Primitive.PrimitivePropertyConfiguration.Configure(IEnumerable
1 propertyMappings, DbProviderManifest providerManifest, Boolean allowOverride,布尔型 fillFromExistingConfiguration) +94
System.Data.Entity.ModelConfiguration.Configuration.Types.StructuralTypeConfiguration.ConfigurePropertyMappings(IList1 propertyMappings, DbProviderManifest providerManifest, Boolean allowOverride) +154
System.Data.Entity.ModelConfiguration.Configuration.Types.EntityTypeConfiguration.ConfigurePropertyMappings(DbDatabaseMapping databaseMapping, EntityType entityType, DbProviderManifest providerManifest, Boolean allowOverride) +585
System.Data.Entity.ModelConfiguration.Configuration.Types.EntityTypeConfiguration.Configure(EntityType entityType, DbDatabaseMapping databaseMapping, DbProviderManifest providerManifest) +177
System.Data.Entity.ModelConfiguration.Configuration.ModelConfiguration.ConfigureEntityTypes(DbDatabaseMapping databaseMapping, ICollection
1 entitySets,DbProviderManifest 供应商清单)+423
System.Data.Entity.ModelConfiguration.Configuration.ModelConfiguration.Configure(DbDatabaseMapping 数据库映射,DbProviderManifest providerManifest) +376
System.Data.Entity.DbModelBuilder.Build(DbProviderManifest providerManifest, DbProviderInfo providerInfo) +444
System.Data.Entity.DbModelBuilder.Build(DbConnection 提供者连接)+55
System.Data.Entity.Internal.LazyInternalContext.CreateModel(LazyInternalContext 内部上下文)+61
System.Data.Entity.Internal.RetryLazy2.GetValue(TInput input) +123
System.Data.Entity.Internal.LazyInternalContext.InitializeContext() +616 System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType) +18
System.Data.Entity.Internal.Linq.InternalSet
1.Initialize() +53
System.Data.Entity.Internal.Linq.InternalSet1.get_InternalContext() +16 System.Data.Entity.Infrastructure.DbQuery1.System.Linq.IQueryable.get_Provider() +39 System.Data.Entity.QueryableExtensions.FirstOrDefaultAsync(IQueryable1 source, Expression1 谓词,CancellationToken cancelToken) +154 System.Data.Entity.QueryableExtensions.FirstOrDefaultAsync(IQueryable1 source, Expression1 谓词)+163
Microsoft.AspNet.Identity.EntityFramework.d__6c.MoveNext() +472 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(任务 任务)+99
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务 任务)+58 Microsoft.AspNet.Identity.CultureAwaiter1.GetResult() +59 Microsoft.AspNet.Identity.<ValidateUserName>d__4.MoveNext() +594 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +99
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58 Microsoft.AspNet.Identity.<ValidateAsync>d__0.MoveNext() +266 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +99
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58 Microsoft.AspNet.Identity.<CreateAsync>d__0.MoveNext() +568 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +99
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58 Microsoft.AspNet.Identity.<CreateAsync>d__d.MoveNext() +483 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +99
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58 System.Runtime.CompilerServices.TaskAwaiter
1.GetResult() +28 BookIT.Controllers.d__15.MoveNext() 在 D:\Projekti\CS\BookIT\BookIT\Controllers\AccountController.cs:155
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(任务 任务)+99
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务 任务)+58
System.Web.Mvc.Async.TaskAsyncActionDescriptor.EndExecute(IAsyncResult asyncResult) +97
System.Web.Mvc.Async.c__DisplayClass37.b__36(IAsyncResult 异步结果)+17
System.Web.Mvc.Async.WrappedAsyncResult1.CallEndDelegate(IAsyncResult asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResultBase
1.End() +49
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +32
System.Web.Mvc.Async.AsyncInvocationWithFilters.b__3d() +50 System.Web.Mvc.Async.c__DisplayClass46.b__3f() +225 System.Web.Mvc.Async.c__DisplayClass33.b__32(IAsyncResult asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResult1.CallEndDelegate(IAsyncResult asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResultBase
1.End() +49
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +34
System.Web.Mvc.Async.c__DisplayClass2b.b__1c() +26 System.Web.Mvc.Async.c__DisplayClass21.b__1e(IAsyncResult asyncResult) +100
System.Web.Mvc.Async.WrappedAsyncResult1.CallEndDelegate(IAsyncResult asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResultBase
1.End() +49
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +27
System.Web.Mvc.Controller.b__1d(IAsyncResult asyncResult,ExecuteCoreState 内部状态)+13
System.Web.Mvc.Async.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult asyncResult) +29
System.Web.Mvc.Async.WrappedAsyncResultBase
1.End() +49
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +36 System.Web.Mvc.Controller.b__15(IAsyncResult asyncResult,控制器控制器)+12
System.Web.Mvc.Async.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult asyncResult) +22
System.Web.Mvc.Async.WrappedAsyncResultBase
1.End() +49
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +26
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10
System.Web.Mvc.MvcHandler.b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +21
System.Web.Mvc.Async.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult asyncResult) +29
System.Web.Mvc.Async.WrappedAsyncResultBase
1.End() +49
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +28 System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult 结果)+9
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9711525 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155

提前致谢

添加:

  if (ModelState.IsValid)
        {
            var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
            var result = await UserManager.CreateAsync(user, model.Password);
            if (result.Succeeded)
            {

【问题讨论】:

  • 你检查过 InnerException 消息了吗?
  • 顺便说一句,您在 BookmarkTag 的复合键中不需要 BookmarkTagId。只要 BookmarkId 和 TagId 就足够了。
  • 您能否添加实际上在这些模型中引发错误的代码?您的堆栈跟踪表明它在 AccountController:155 附近。根据异常文本,您似乎正在调用 .Single() 或 .First() 但如果不查看实际代码,我们无法知道这一点。
  • 是的,它在该行抛出了错误,但除了我自己放置在那里的模型之外,我没有更改代码中的任何内容,当我删除这些模型时,注册会通过......当您创建新的 mvc 程序并检查个人帐户选项时,其余代码是默认的 @CodeNotFound 是的,我知道我只是把它放在那里,因为我想添加一个额外的列
  • @IvanRepusic 那么你给 Single() 或 First() 方法的谓词是什么?

标签: c# asp.net-mvc entity-framework


【解决方案1】:

最后我找到了导致错误的原因... 就是这条线

 [Column(TypeName="varchar(60)")]
public string TagName { get; set; }

当我删除 Column(TypeName) 部分时,代码可以毫无问题地进行编译...它现在可以工作,但我不确定它为什么会这样或为什么会抛出该错误。谁能解释为什么它以前不起作用?

【讨论】:

    【解决方案2】:

    您的 Key 属性太多,EF 框架无法计算出您的模型。您可以使用 fluent api 来准确配置您想要的内容。解决问题的最简单方法是使用 EF 功能约定优于配置。基本上,遵循约定,EF 框架将为您完成繁重的工作。我在这里添加了一个配置方法的约定,它至少在我的视觉工作室中运行。我已经对此进行了测试,并且运行成功。

    public class Bookmark
    {
       public int BookmarkID { get; set; }
       public string Url { get; set; }
       public ApplicationUser UserId { get; set; }
       public virtual ICollection<BookmarkTag> BookmarkTags { get; set; }
     }
    
     public class BookmarkTag
     {
        public int BookmarkTagID { get; set; }
        public virtual Bookmark Bookmark { get; set; }
        public virtual Tag Tag { get; set; }
     }
    
     public class Tag
     {
        public int TagID { get; set; }
        public string TagName { get; set; }
        public virtual ICollection<BookmarkTag> BookmarkTags { get; set; }
     }
    

    【讨论】:

    • 抱歉回复晚了,但这也无法解决问题,我再次遇到同样的错误
    猜你喜欢
    • 2021-08-28
    • 1970-01-01
    • 2017-05-06
    • 1970-01-01
    • 2015-01-01
    • 2021-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多