我有一個看起來像這樣的實體EF6的Code First模型:DbSet <T>。新增(T實體)拋出System.InvalidOperationException:序列不包含任何匹配的元素
[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()
需要找到匹配的元素。有人可以向我解釋這裏存在的問題,以及我應該怎麼做來糾正它?
UPDATE
每請求,以下是我的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
顯示你的'Web/App.config'。看起來''Column(TypeName =「varchar(max)」)]''屬性中的'varchar(max)'與任何配置的存儲類型都不匹配。你在Add()方法得到這個結果的原因很簡單,因爲這是你第一次訪問'DbSet',然後調用它的內部'Initialize()'方法。 – haim770
由於包含商業敏感數據,我無法展示整個事情。有什麼具體的你想看?這是針對SQL Server實例的,所以我會假定'varchar(max)'適合於此。 –
嘗試更改'[Column(「Comments」,TypeName =「varchar」)] [[Column(TypeName =「varchar(max)」)]'' –