1

The OfType part of the query doesn't work as expected, and there’s an error when saving changes in the database.

Code:

using System;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration;
using System.Linq;

namespace ConsoleApp1
{
    internal class Program
    {
        static void Main(string[] args)
        {
            try
            {
                var db = new ToutiaoDbContext();
                var query = db.Collections.OfType<NewsCollection>();
                var list = query.ToList();
                var entity = list.FirstOrDefault();
                entity.Title = "title123";
                var res = db.SaveChanges();

                Console.WriteLine(res);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }

        }
    }


    public class ToutiaoDbContext : DbContext
    {
        public ToutiaoDbContext()
            : base("xxx")
        {

        }

        public DbSet<Collection> Collections { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Configurations.Add(new CollectionDbMap());

            base.OnModelCreating(modelBuilder);
        }
    }


    public class CollectionDbMap : EntityTypeConfiguration<Collection>
    {
        public CollectionDbMap()
        {
            ToTable("WWW_COLLECTION");
            HasKey(co => new { co.ColType, co.UserSn, co.ItemId });
            Property(co => co.ColType).HasColumnName("COL_TYPE");
            Property(co => co.UserSn).HasColumnName("USER_SN");
            Property(co => co.ItemId).HasColumnName("ITEM_ID");
            Property(co => co.CreatedBy).HasColumnName("CREATED_BY");
            Property(co => co.CreatedDate).HasColumnName("CREATED_DATE");
            Property(co => co.Title).HasColumnName("TITLE");
            Map<NewsCollection>(co => co.Requires("ColType").HasValue(19999));
        }
    }
    public abstract class Collection
    {
        public virtual int ColType { get; protected set; }
        public int UserSn { get; set; }
        public int ItemId { get; set; }
        public int CreatedBy { get; set; }
        public DateTime CreatedDate { get; set; }
        public string Title { get; set; }
    }
    public class NewsCollection : Collection
    {
        // public override int ColType => 19999;
    }
}

Error Message:

System.Data.Entity.Infrastructure.DbUpdateException: Error retrieving values from ObjectStateEntry. See inner exception for details.
 ---> System.Data.Entity.Core.UpdateException: Error retrieving values from ObjectStateEntry. See inner exception for details.
 ---> System.Data.Entity.Core.MappingException:
(6,10) : error 3032: Problem in mapping fragments starting at line 6:Condition member 'Collection.COL_TYPE' with a condition other than 'IsNull=False' is mapped. Either remove the condition on Collection.COL_TYPE or remove it from the mapping.

(16,10) : error 3032: Problem in mapping fragments starting at line 16:Condition member 'Collection.COL_TYPE' with a condition other than 'IsNull=False' is mapped. Either remove the condition on Collection.COL_TYPE or remove it from the mapping.

   at System.Data.Entity.Core.Mapping.StorageMappingItemCollection.ViewDictionary.SerializedGenerateViews(EntityContainerMapping entityContainerMap, Dictionary`2 resultDictionary) in C:\WorkSpace\0-OpenSource\ef6\src\EntityFramework\Core\Mapping\StorageMappingItemCollection.cs:line 144
   at System.Data.Entity.Core.Mapping.StorageMappingItemCollection.ViewDictionary.SerializedGetGeneratedViews(EntityContainer container) in C:\WorkSpace\0-OpenSource\ef6\src\EntityFramework\Core\Mapping\StorageMappingItemCollection.cs:line 118
   at System.Data.Entity.Core.Common.Utils.Memoizer`2.<>c__DisplayClass4_0.<Evaluate>b__0() in C:\WorkSpace\0-OpenSource\ef6\src\EntityFramework\Core\Common\Utils\Memoizer.cs:line 58
   at System.Data.Entity.Core.Common.Utils.Memoizer`2.Result.GetValue() in C:\WorkSpace\0-OpenSource\ef6\src\EntityFramework\Core\Common\Utils\Memoizer.cs:line 134
   at System.Data.Entity.Core.Common.Utils.Memoizer`2.Evaluate(TArg arg) in C:\WorkSpace\0-OpenSource\ef6\src\EntityFramework\Core\Common\Utils\Memoizer.cs:line 70
   at System.Data.Entity.Core.Mapping.StorageMappingItemCollection.ViewDictionary.GetGeneratedView(EntitySetBase extent, MetadataWorkspace workspace, StorageMappingItemCollection storageMappingItemCollection) in C:\WorkSpace\0-OpenSource\ef6\src\EntityFramework\Core\Mapping\StorageMappingItemCollection.cs:line 367
   at System.Data.Entity.Core.Mapping.StorageMappingItemCollection.GetGeneratedView(EntitySetBase extent, MetadataWorkspace workspace) in C:\WorkSpace\0-OpenSource\ef6\src\EntityFramework\Core\Mapping\StorageMappingItemCollection.cs:line 1085
   at System.Data.Entity.Core.Mapping.Update.Internal.ViewLoader.InitializeEntitySet(EntitySetBase entitySetBase, MetadataWorkspace workspace) in C:\WorkSpace\0-OpenSource\ef6\src\EntityFramework\Core\Mapping\Update\Internal\ViewLoader.cs:line 167
   at System.Data.Entity.Core.Mapping.Update.Internal.ViewLoader.SyncInitializeEntitySet[TArg,TResult](EntitySetBase entitySetBase, MetadataWorkspace workspace, Func`2 evaluate, TArg arg) in C:\WorkSpace\0-OpenSource\ef6\src\EntityFramework\Core\Mapping\Update\Internal\ViewLoader.cs:line 150
   at System.Data.Entity.Core.Mapping.Update.Internal.ViewLoader.SyncContains[T_Element](EntitySetBase entitySetBase, MetadataWorkspace workspace, Set`1 set, T_Element element) in C:\WorkSpace\0-OpenSource\ef6\src\EntityFramework\Core\Mapping\Update\Internal\ViewLoader.cs:line 115
   at System.Data.Entity.Core.Mapping.Update.Internal.ViewLoader.IsServerGen(EntitySetBase entitySetBase, MetadataWorkspace workspace, EdmMember member) in C:\WorkSpace\0-OpenSource\ef6\src\EntityFramework\Core\Mapping\Update\Internal\ViewLoader.cs:line 86
   at System.Data.Entity.Core.Mapping.Update.Internal.ExtractorMetadata..ctor(EntitySetBase entitySetBase, StructuralType type, UpdateTranslator translator) in C:\WorkSpace\0-OpenSource\ef6\src\EntityFramework\Core\Mapping\Update\Internal\ExtractorMetadata.cs:line 86
   at System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.GetExtractorMetadata(EntitySetBase entitySetBase, StructuralType type) in C:\WorkSpace\0-OpenSource\ef6\src\EntityFramework\Core\Mapping\Update\Internal\UpdateTranslator.cs:line 738
   at System.Data.Entity.Core.Mapping.Update.Internal.ExtractorMetadata.ExtractResultFromRecord(IEntityStateEntry stateEntry, Boolean isModified, IExtendedDataRecord record, Boolean useCurrentValues, UpdateTranslator translator, ModifiedPropertiesBehavior modifiedPropertiesBehavior) in C:\WorkSpace\0-OpenSource\ef6\src\EntityFramework\Core\Mapping\Update\Internal\ExtractorMetadata.cs:line 298
   at System.Data.Entity.Core.Mapping.Update.Internal.RecordConverter.ConvertStateEntryToPropagatorResult(IEntityStateEntry stateEntry, Boolean useCurrentValues, ModifiedPropertiesBehavior modifiedPropertiesBehavior) in C:\WorkSpace\0-OpenSource\ef6\src\EntityFramework\Core\Mapping\Update\Internal\RecordConverter.cs:line 81
   --- End of inner exception stack trace ---
   at System.Data.Entity.Core.Mapping.Update.Internal.RecordConverter.ConvertStateEntryToPropagatorResult(IEntityStateEntry stateEntry, Boolean useCurrentValues, ModifiedPropertiesBehavior modifiedPropertiesBehavior) in C:\WorkSpace\0-OpenSource\ef6\src\EntityFramework\Core\Mapping\Update\Internal\RecordConverter.cs:line 90
   at System.Data.Entity.Core.Mapping.Update.Internal.RecordConverter.ConvertOriginalValuesToPropagatorResult(IEntityStateEntry stateEntry, ModifiedPropertiesBehavior modifiedPropertiesBehavior) in C:\WorkSpace\0-OpenSource\ef6\src\EntityFramework\Core\Mapping\Update\Internal\RecordConverter.cs:line 48
   at System.Data.Entity.Core.Mapping.Update.Internal.ExtractedStateEntry..ctor(UpdateTranslator translator, IEntityStateEntry stateEntry) in C:\WorkSpace\0-OpenSource\ef6\src\EntityFramework\Core\Mapping\Update\Internal\ExtractedStateEntry.cs:line 49
   at System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.LoadStateEntry(IEntityStateEntry stateEntry) in C:\WorkSpace\0-OpenSource\ef6\src\EntityFramework\Core\Mapping\Update\Internal\UpdateTranslator.cs:line 1068
   at System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.PullModifiedEntriesFromStateManager() in C:\WorkSpace\0-OpenSource\ef6\src\EntityFramework\Core\Mapping\Update\Internal\UpdateTranslator.cs:line 836
   at System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.ProduceCommands() in C:\WorkSpace\0-OpenSource\ef6\src\EntityFramework\Core\Mapping\Update\Internal\UpdateTranslator.cs:line 491
   at System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.Update() in C:\WorkSpace\0-OpenSource\ef6\src\EntityFramework\Core\Mapping\Update\Internal\UpdateTranslator.cs:line 407
   at System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.<>c.<Update>b__21_0(UpdateTranslator ut) in C:\WorkSpace\0-OpenSource\ef6\src\EntityFramework\Core\EntityClient\Internal\EntityAdapter.cs:line 74
   at System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.Update[T](T noChangesResult, Func`2 updateFunction) in C:\WorkSpace\0-OpenSource\ef6\src\EntityFramework\Core\EntityClient\Internal\EntityAdapter.cs:line 117
   at System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.Update() in C:\WorkSpace\0-OpenSource\ef6\src\EntityFramework\Core\EntityClient\Internal\EntityAdapter.cs:line 74
   at System.Data.Entity.Core.Objects.ObjectContext.<SaveChangesToStore>b__153_0() in C:\WorkSpace\0-OpenSource\ef6\src\EntityFramework\Core\Objects\ObjectContext.cs:line 3168
   at System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess) in C:\WorkSpace\0-OpenSource\ef6\src\EntityFramework\Core\Objects\ObjectContext.cs:line 3272
   at System.Data.Entity.Core.Objects.ObjectContext.SaveChangesToStore(SaveOptions options, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction) in C:\WorkSpace\0-OpenSource\ef6\src\EntityFramework\Core\Objects\ObjectContext.cs:line 3166
   at System.Data.Entity.Core.Objects.ObjectContext.<>c__DisplayClass148_1.<SaveChangesInternal>b__0() in C:\WorkSpace\0-OpenSource\ef6\src\EntityFramework\Core\Objects\ObjectContext.cs:line 3039
   at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation) in C:\WorkSpace\0-OpenSource\ef6\src\EntityFramework.SqlServer\DefaultSqlExecutionStrategy.cs:line 43
   at System.Data.Entity.Core.Objects.ObjectContext.SaveChangesInternal(SaveOptions options, Boolean executeInExistingTransaction) in C:\WorkSpace\0-OpenSource\ef6\src\EntityFramework\Core\Objects\ObjectContext.cs:line 3038
   at System.Data.Entity.Core.Objects.ObjectContext.SaveChanges(SaveOptions options) in C:\WorkSpace\0-OpenSource\ef6\src\EntityFramework\Core\Objects\ObjectContext.cs:line 3017
   at System.Data.Entity.Internal.InternalContext.SaveChanges() in C:\WorkSpace\0-OpenSource\ef6\src\EntityFramework\Internal\InternalContext.cs:line 437
   --- End of inner exception stack trace ---
   at System.Data.Entity.Internal.InternalContext.SaveChanges() in C:\WorkSpace\0-OpenSource\ef6\src\EntityFramework\Internal\InternalContext.cs:line 441
   at System.Data.Entity.Internal.LazyInternalContext.SaveChanges() in C:\WorkSpace\0-OpenSource\ef6\src\EntityFramework\Internal\LazyInternalContext.cs:line 202
   at System.Data.Entity.DbContext.SaveChanges() in C:\WorkSpace\0-OpenSource\ef6\src\EntityFramework\DbContext.cs:line 351
   at ConsoleApp1.Program.Main(String[] args) in C:\WorkSpace\0-OpenSource\ef6\ConsoleApp1\Program.cs:line 19

The original project has already adopted an abstract class design pattern, which makes it difficult to modify. How should I address this error?

3
  • On a hunch looking at the documentation, can you try replacing co => co.Requires("ColType") with co => co.Requires("COL_TYPE") ? The doco for the .Requires mentions "name of the discriminator column" which implies it may not be looking at the entity.ColType property mapping to resolve the column. Commented Jul 10, 2024 at 22:18
  • This does not work. It might even cause an earlier error. An error occurs during the query. COL_TYPE: Name: Each property name in a type must be unique. Property name 'COL_TYPE' is already defined. Commented Jul 11, 2024 at 3:13
  • AFAIK you cannot have the discriminator mapped as a property, even as part of the PK. Try removing that property and replace the PK declaration with HasKey("COL_TYPE" , "USER_SN", "ITEM_ID"). From what I can see it may be possible to use a shadow property for the ColType which may allow the property name but still a magic string. I prefer avoiding the magic string methods as it's confusing whether to use the property name or table column name, plus doesn't update as code gets re-factored. Commented Jul 11, 2024 at 4:31

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.