DbSet<T>.Add(T entity) throws System.InvalidOperationException: Sequence contains no matching element
DbSet<T>.Add(T entity) throws System.InvalidOperationException: Sequence contains no matching element
我有一个 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; }
}
我的数据库上下文 class 看起来像这样:
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
所以我想我应该早点提到这一点,我不知道它是否重要(但根据建议的发展方向,它看起来可能是),但我指的是预-现有数据库。有问题的 table 是这样创建的:
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
尝试改变
[Column(TypeName="varchar(max)")]
public string Comments { get; set; }
到
[Column(TypeName="[varchar](MAX) NULL")]
public string Comments { get; set; }
所以这是几件事的结合。
- 我的迁移处于一种奇怪的状态;因为我的主要(启动)
项目与我的数据访问项目不同,并且有
其中包含不同的连接字符串,EF 绝对拒绝
即使在包管理器控制台中明确告知要处理哪个项目,也能正确生成迁移代码,同样荒谬
错误...我无意中偶然发现了这个,我很生气
与问题相比,消息的神秘性质。
- 我想多了
MAX
值;事实证明 EF6 默认为
NVARCHAR(MAX)
对于所有字符串列,除非明确说明
否则(我个人认为这是一个非常糟糕的主意)——或者
我猜是通过惯例。只需指定 VARCHAR
然后
调整迁移代码,我可以获得 VARCHAR(MAX)
... 全部
NVARCHAR(MAX)
不合适的字符串属性,我不得不
放入 StringLength
个装饰器。
所以最后,我现在有新的神秘错误...但这是另一个问题。感谢大家的帮助。
我有一个 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; }
}
我的数据库上下文 class 看起来像这样:
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
所以我想我应该早点提到这一点,我不知道它是否重要(但根据建议的发展方向,它看起来可能是),但我指的是预-现有数据库。有问题的 table 是这样创建的:
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
尝试改变
[Column(TypeName="varchar(max)")]
public string Comments { get; set; }
到
[Column(TypeName="[varchar](MAX) NULL")]
public string Comments { get; set; }
所以这是几件事的结合。
- 我的迁移处于一种奇怪的状态;因为我的主要(启动) 项目与我的数据访问项目不同,并且有 其中包含不同的连接字符串,EF 绝对拒绝 即使在包管理器控制台中明确告知要处理哪个项目,也能正确生成迁移代码,同样荒谬 错误...我无意中偶然发现了这个,我很生气 与问题相比,消息的神秘性质。
- 我想多了
MAX
值;事实证明 EF6 默认为NVARCHAR(MAX)
对于所有字符串列,除非明确说明 否则(我个人认为这是一个非常糟糕的主意)——或者 我猜是通过惯例。只需指定VARCHAR
然后 调整迁移代码,我可以获得VARCHAR(MAX)
... 全部NVARCHAR(MAX)
不合适的字符串属性,我不得不 放入StringLength
个装饰器。
所以最后,我现在有新的神秘错误...但这是另一个问题。感谢大家的帮助。