gpt4 book ai didi

c# - DbSet.Add(T 实体) 抛出 System.InvalidOperationException : Sequence contains no matching element

转载 作者:太空宇宙 更新时间:2023-11-03 17:00:58 24 4
gpt4 key购买 nike

我有一个 EF6 Code First 模型,其实体如下所示:

[Table("Updates")]
public class Update
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Key]
public Guid Id { get; set; }

[Required]
public string CreatedBy { get; set; }

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

[Required]
public DateTime CreatedTimestampUtc { get; set; }
}

我的数据库上下文类如下所示:

public class MyContext : DbContext, IUnitOfWork
{
private static readonly string ConnectionString = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;

public GlobalizationContext() : base(ConnectionString)
{
}

public DbSet<Update> UpdatesDbSet { get; set; }

public IQueryable<Update> Updates //IUnitOfWork implementation
{
get { return UpdatesDbSet; }
}

public async Task AddUpdateTokenAsync(Update updateToken)
{
var entity = UpdatesDbSet.Add(updateToken);
var result = await SaveChangesAsync();
}
}

当我点击 var entity = UpdatesDbSet.Add(updateToken); 行时,我生成了以下异常:

SetUpdateTokenAsync(Update) System.InvalidOperationException: Sequence contains no matching element
at System.Linq.Enumerable.Single[TSource](IEnumerable`1 source, Func`2 predicate)
at System.Data.Entity.Utilities.DbProviderManifestExtensions.GetStoreTypeFromName(DbProviderManifest providerManifest, String name)
at System.Data.Entity.ModelConfiguration.Configuration.Properties.Primitive.PrimitivePropertyConfiguration.ConfigureColumn(EdmProperty column, EntityType table, DbProviderManifest providerManifest)
at System.Data.Entity.ModelConfiguration.Configuration.Properties.Primitive.PrimitivePropertyConfiguration.Configure(EdmProperty column, EntityType table, DbProviderManifest providerManifest, Boolean allowOverride, Boolean fillFromExistingConfiguration)
at System.Data.Entity.ModelConfiguration.Configuration.Properties.Primitive.PrimitivePropertyConfiguration.<>c__DisplayClass4.<Configure>b__3(Tuple`2 pm)
at System.Data.Entity.Utilities.IEnumerableExtensions.Each[T](IEnumerable`1 ts, Action`1 action)
at System.Data.Entity.ModelConfiguration.Configuration.Properties.Primitive.PrimitivePropertyConfiguration.Configure(IEnumerable`1 propertyMappings, DbProviderManifest providerManifest, Boolean allowOverride, Boolean fillFromExistingConfiguration)
at System.Data.Entity.ModelConfiguration.Configuration.Types.StructuralTypeConfiguration.ConfigurePropertyMappings(IList`1 propertyMappings, DbProviderManifest providerManifest, Boolean allowOverride)
at System.Data.Entity.ModelConfiguration.Configuration.Types.EntityTypeConfiguration.ConfigurePropertyMappings(DbDatabaseMapping databaseMapping, EntityType entityType, DbProviderManifest providerManifest, Boolean allowOverride)
at System.Data.Entity.ModelConfiguration.Configuration.Types.EntityTypeConfiguration.Configure(EntityType entityType, DbDatabaseMapping databaseMapping, DbProviderManifest providerManifest)
at System.Data.Entity.ModelConfiguration.Configuration.ModelConfiguration.ConfigureEntityTypes(DbDatabaseMapping databaseMapping, ICollection`1 entitySets, DbProviderManifest providerManifest)
at System.Data.Entity.ModelConfiguration.Configuration.ModelConfiguration.Configure(DbDatabaseMapping databaseMapping, DbProviderManifest providerManifest)
at System.Data.Entity.DbModelBuilder.Build(DbProviderManifest providerManifest, DbProviderInfo providerInfo)
at System.Data.Entity.DbModelBuilder.Build(DbConnection providerConnection)
at System.Data.Entity.Internal.LazyInternalContext.CreateModel(LazyInternalContext internalContext)
at System.Data.Entity.Internal.RetryLazy`2.GetValue(TInput input)
at System.Data.Entity.Internal.LazyInternalContext.InitializeContext()
at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)
at System.Data.Entity.Internal.Linq.InternalSet`1.Initialize()
at System.Data.Entity.Internal.Linq.InternalSet`1.get_InternalContext()
at System.Data.Entity.Internal.Linq.InternalSet`1.ActOnSet(Action action, EntityState newState, Object entity, String methodName)
at System.Data.Entity.Internal.Linq.InternalSet`1.Add(Object entity)
at System.Data.Entity.DbSet`1.Add(TEntity entity)

查看DbSet对象和Update对象,好像都是实例化的,不明白为什么.Add() 需要找到匹配的元素。有人可以向我解释这里的问题是什么,我应该如何纠正它?

更新

根据请求,以下是我的 web.config 文件中的 EF 配置:

<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
. . .
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="mssqllocaldb" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>

...我意识到这是错误的,并将其更改为:

<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>

这并没有改变症状。我还尝试了建议的装饰器更改如下:

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

...同样,行为没有区别。

更新 2

所以我想我应该早点提到这个,我不知道它是否重要(但根据建议的方向,它看起来可能是),但我指的是一个预先存在的数据库.有问题的表是这样创建的:

CREATE TABLE [dbo].[Updates](
[Id] [uniqueidentifier] NOT NULL,
[CreatedTimestampUtc] [datetime] NOT NULL,
[Comments] [varchar](MAX) NULL,
[CreatedBy] [nvarchar](260) NOT NULL,
CONSTRAINT [PK_Updates] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

SET ANSI_PADDING ON
GO

ALTER TABLE [dbo].[Updates] ADD CONSTRAINT [DF_Updates_Id] DEFAULT (newid()) FOR [Id]
GO

ALTER TABLE [dbo].[Updates] ADD CONSTRAINT [DF_Updates_CreatedTimestampUtc] DEFAULT (getutcdate()) FOR [CreatedTimestampUtc]
GO

ALTER TABLE [dbo].[Updates] ADD CONSTRAINT [DF_Updates_CreatedBy] DEFAULT (suser_sname()) FOR [CreatedBy]
GO

最佳答案

所以这是几件事的结合。

  • 我的迁移处于一种奇怪的状态;因为我的主要(启动)项目与我的数据访问项目不同,并且有其中包含不同的连接字符串,EF 绝对拒绝即使在包管理器控制台中明确告知要处理哪个项目,也能正确生成迁移代码,同样荒谬错误...我无意中偶然发现了这个,我很生气与问题相比,消息的神秘性质。
  • 我对 MAX 值想得太多了;事实证明 EF6 默认为NVARCHAR(MAX) 用于所有字符串列,除非明确说明否则(我个人认为这是一个非常糟糕的主意)——或者我猜是通过惯例。只需指定 VARCHAR 然后调整迁移代码,我可以获得 VARCHAR(MAX)... for allNVARCHAR(MAX) 不合适的字符串属性,我不得不放入 StringLength 装饰器。

最后,我现在有了新的神秘错误……但那是另一个问题。感谢大家的帮助。

关于c# - DbSet<T>.Add(T 实体) 抛出 System.InvalidOperationException : Sequence contains no matching element,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34053051/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com