The property 'PropertyName' could not be mapped, because it is of type 'List'

后端 未结 2 1732
囚心锁ツ
囚心锁ツ 2020-12-20 20:03

I got this problem when I try to create the database with EntityFramework Core:

The property \'Rating.RatingScores\' could not be mapped, because it i

2条回答
  •  孤城傲影
    2020-12-20 20:29

    When you really need to put multiple values in single column can use below way

    Let's say you want to create only one table for below class

    public class SomeClass
    {
        public Guid ID { get; set; }
        public IEnumerable Values { get; set; }
    }
    

    First create a converter, which will control .net values to db values and vice versa

        using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
     
        public class IntListToStringValueConverter : ValueConverter, string>
        {
            public IntListToStringValueConverter() : base(le => ListToString(le), (s => StringToList(s)))
            {
    
            }
            public static string ListToString(IEnumerable value)
            {
                if (value.IsEmptyCollection())
                {
                    return null;
                }
     
                return value.Join(',');
            }
    
            public static IEnumerable StringToList(string value)
            {  
                if (value.IsNullOrEmpty())
                {
                    return null;
                }
    
                return value.Split(',').Select(i => Convert.ToInt32(i)); ; 
                
            }
        }
    

    And DbContext should have below method

     protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
             .....
    
            var IntValueConverter = new IntListToStringValueConverter();
    
            modelBuilder
                .Entity()
                .Property(e => e.Values)//Property
                .HasConversion(IntValueConverter);
    
        }
    

    Done!! IT should work

提交回复
热议问题