DbSet <t> .Add(T entity)抛出System.InvalidOperationException:Sequence不包含匹配元素

时间:2015-12-02 21:10:09

标签: c# entity-framework ef-code-first

我有一个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; }
}

我的db上下文类看起来像这样:

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

2 个答案:

答案 0 :(得分:0)

所以这是几件事的结合。

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

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

答案 1 :(得分:-1)

尝试更改

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

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