2015-12-02 47 views
2

我有一個看起來像這樣的實體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 
+0

顯示你的'Web/App.config'。看起來''Column(TypeName =「varchar(max)」)]''屬性中的'varchar(max)'與任何配置的存儲類型都不匹配。你在Add()方法得到這個結果的原因很簡單,因爲這是你第一次訪問'DbSet',然後調用它的內部'Initialize()'方法。 – haim770

+0

由於包含商業敏感數據,我無法展示整個事情。有什麼具體的你想看?這是針對SQL Server實例的,所以我會假定'varchar(max)'適合於此。 –

+0

嘗試更改'[Column(「Comments」,TypeName =「varchar」)] [[Column(TypeName =「varchar(max)」)]'' –

回答

0

因此,這是一個幾件事情的組合。

  • 我的遷徙處於一種奇怪的狀態;因爲我的主(啓動) 項目是不一樣的我的數據訪問項目,並有在他們 不同的連接字符串,EF絕不肯 正確生成遷移代碼,即使在包管理器控制檯該項目明確告知工作過的,具有相同的可笑 錯誤...我碰到這個偶然意外,我是相當惱火 在消息的神祕性相比問題。
  • 我正在超過MAX值;原來EF6默認爲 NVARCHAR(MAX)所有字符串列,除非明確說明 否則(我個人認爲這是一個非常糟糕的主意) - 或 通過約定,我想。通過指定只是和VARCHAR然後 調整遷移代碼,我能得到VARCHAR(MAX) ...所有 字符串屬性,其中NVARCHAR(MAX)是不恰當的,我不得不 放於StringLength裝飾。

因此,最後,我現在有新的神祕錯誤......但這是另一個問題。感謝大家的幫助。

-1

試圖改變

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

[Column(TypeName="[varchar](MAX) NULL")] 
public string Comments { get; set; } 
+0

這似乎無法解決問題。 –

+0

你能否刪除該列,並查看該列是否有問題。 – skalinkin

+0

也嘗試更改Id列以將Guid類型和UpdateId作爲名稱或將其更改爲int類型。使用Guid類型的uniqueidentifier可能存在問題 – skalinkin

相關問題