数据库集<;T>;.Add(T实体)引发System.InvalidOperationException:序列不

本文关键字:InvalidOperationException System 引发 lt gt Add 实体 数据库 | 更新日期: 2023-09-27 18:25:34

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

数据库集<;T>;.Add(T实体)引发System.InvalidOperationException:序列不

所以这是两件事的结合。

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

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

尝试更改

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

[Column(TypeName="[varchar](MAX) NULL")]
public string Comments { get; set; }
相关文章:
  • 没有找到相关文章