c# - EF Core 2.0 - 添加时出现 System.NotSupportedException

标签 c# sql-server entity-framework .net-core entity-framework-core

我正在使用 EF Core 2.0。我有一个包含 4 列的表,其中 PK 由所有 4 列组成。其中一列 (IsDefault) 是数据库中的位字段。如果我插入一条 IsDefault 设置为 true 的记录,一切正常。如果我插入 IsDefault 设置为 false 的记录,则会出现以下异常:

System.NotSupportedException occurred
  HResult=0x80131515
  Message=The 'IsDefault' on entity type 'ChromeMileageRestrictionTest' does not have a value set and no value generator is available for properties of type 'bool'. Either set a value for the property before adding the entity or configure a value generator for properties of type 'bool'.
  Source=<Cannot evaluate the exception source>
  StackTrace:
   at Microsoft.EntityFrameworkCore.ValueGeneration.ValueGeneratorSelector.Create(IProperty property, IEntityType entityType)
   at Microsoft.EntityFrameworkCore.ValueGeneration.RelationalValueGeneratorSelector.Create(IProperty property, IEntityType entityType)
   at Microsoft.EntityFrameworkCore.ValueGeneration.Internal.SqlServerValueGeneratorSelector.Create(IProperty property, IEntityType entityType)
   at Microsoft.EntityFrameworkCore.ValueGeneration.ValueGeneratorSelector.<>c__DisplayClass6_0.<Select>b__0(IProperty p, IEntityType e)
   at Microsoft.EntityFrameworkCore.ValueGeneration.ValueGeneratorCache.<>c.<GetOrAdd>b__3_0(CacheKey ck)
   at System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory)
   at Microsoft.EntityFrameworkCore.ValueGeneration.ValueGeneratorCache.GetOrAdd(IProperty property, IEntityType entityType, Func`3 factory)
   at Microsoft.EntityFrameworkCore.ValueGeneration.ValueGeneratorSelector.Select(IProperty property, IEntityType entityType)
   at Microsoft.EntityFrameworkCore.ValueGeneration.Internal.SqlServerValueGeneratorSelector.Select(IProperty property, IEntityType entityType)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.ValueGenerationManager.Generate(InternalEntityEntry entry)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.InternalEntityEntry.SetEntityState(EntityState entityState, Boolean acceptChanges, Boolean forceStateWhenUnknownKey)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.EntityGraphAttacher.PaintAction(EntityEntryGraphNode node)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.EntityEntryGraphIterator.TraverseGraph(EntityEntryGraphNode node, Func`2 handleNode)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.EntityGraphAttacher.AttachGraph(InternalEntityEntry rootEntry, EntityState entityState, Boolean forceStateWhenUnknownKey)
   at Microsoft.EntityFrameworkCore.DbContext.SetEntityState(InternalEntityEntry entry, EntityState entityState)
   at Microsoft.EntityFrameworkCore.DbContext.SetEntityState[TEntity](TEntity entity, EntityState entityState)
   at Microsoft.EntityFrameworkCore.DbContext.Add[TEntity](TEntity entity)
   at DAL.Tests.UnitTest1.TestMethod1() in C:\Users\jkruer\Source\Repos\JLM.App.ChromeIncentivesService\DAL.Tests\UnitTest1.cs:line 12

我创建了一个非常简化的版本,并且能够使用我的单个表、单个实体、单个记录、单个单元测试实现来重现问题。

我的数据库表:

CREATE TABLE [dbo].[ChromeMileageRestrictionTEST](
    [TermID] [varchar](50) NOT NULL,
    [Mileage] [varchar](50) NOT NULL,
    [Residual] [decimal](18, 8) NOT NULL,
    [isDefault] [bit] NOT NULL,
 CONSTRAINT [PK_ChromeMileageRestrictionTEST] PRIMARY KEY CLUSTERED 
(
    [TermID] ASC,
    [Mileage] ASC,
    [Residual] ASC,
    [isDefault] 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

ALTER TABLE [dbo].[ChromeMileageRestrictionTEST] ADD  CONSTRAINT [DF_ChromeMileageRestrictionTEST_Residual]  DEFAULT ((0)) FOR [Residual]
GO

ALTER TABLE [dbo].[ChromeMileageRestrictionTEST] ADD  CONSTRAINT [DF_ChromeMileageRestrictionTEST_isDefault]  DEFAULT ((0)) FOR [isDefault]
GO

我的数据库上下文:

public partial class ReportingContext : DbContext
    {
        public ReportingContext()
        {
        }

        public virtual DbSet<ChromeMileageRestrictionTest> ChromeMileageRestriction { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseSqlServer(@"MyConnectionStringGoesHere");            
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<ChromeMileageRestrictionTest>(entity =>
            {
                entity.HasKey(e => new { e.TermId, e.Mileage, e.Residual, e.IsDefault })                
                .HasName("PK_ChromeMileageRestrictionTest");

                entity.Property(e => e.TermId)
                    .HasColumnName("TermID")
                    .HasMaxLength(50)
                    .IsUnicode(false);

                entity.Property(e => e.Mileage)
                    .HasMaxLength(50)
                    .IsUnicode(false);

                entity.Property(e => e.Residual)
                    .HasColumnType("decimal(18, 8)")
                    .HasDefaultValueSql("((0))");

                entity.Property(e => e.IsDefault)
                    .HasColumnName("isDefault")
                    .HasDefaultValueSql("((0))");
            });
        }
    }

我的实体:

public partial class ChromeMileageRestrictionTest
    {
        public string TermId { get; set; }
        public string Mileage { get; set; }
        public decimal Residual { get; set; }
        public bool IsDefault { get; set; }
    }

我的单元测试:

[TestClass]
    public class UnitTest1
    {
        [TestMethod]
        public void TestMethod1()
        {
            var dbContext = new ReportingContext();
            dbContext.Add(new ChromeMileageRestrictionTest 
            {
                TermId = "6078915-0-0",
                Mileage = "15,000",
                Residual = 45.00000000M,
                IsDefault = true //THIS WORKS
            });
            dbContext.Add(new ChromeMileageRestrictionTest 
            {
                TermId = "6078915-0-0",
                Mileage = "15,000",
                Residual = 45.00000000M,
                IsDefault = false //THIS THROWS AN EXCEPTION
            });
            dbContext.SaveChanges();
        }
    }

我已经为这个问题摸不着头脑有一段时间了。我想不通。非常感谢任何帮助!

谢谢!

最佳答案

此内容的重复项:Entity Framework not including columns with default value in insert into query

TLDR:我从数据库和 DbContext 映射中删除了 IsDefault 字段上的默认值 False。这解决了问题。

关于c# - EF Core 2.0 - 添加时出现 System.NotSupportedException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46571347/

相关文章:

c# - 在 DLL 中为参数添加注释

c# - TimeSpan.ToString ("hh:mm") 错误

c# - 当数据已在数据库中时 EF 种子不起作用

c# - 架构 ASP.NET MVC 5

sql-server - 在SSRS矩阵报告中获取前20行,其余的排在第21行

c#通用转换器

c# - 使用 Linq-to-SQL 插入有时会失败

entity-framework - DBContext DBSet 查询和无跟踪选项

c# - 如何在 Entity Framework 中一次调用使用 UNION(concat/union)?

javascript - 如何使用 EDMX 文件生成 UI