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

后端 未结 2 1719
囚心锁ツ
囚心锁ツ 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:28

    If the Rating class has multiple RatingScores you have a one-to-many relationship and the RatingScores property needs its own table, you therefore need to create a new class.

    Class RatingScore 
    {
      public int Id { get; set; }
      public decimal RtSc { get; set; }
    }
    

    Then the Rating property will look like this:

    public List<RatingScore> MyRatingScores { get; set; }
    

    However if each Rating has one RatingScore, your property should not be a collection.

    public RatingScore MyRatingScore { get; Set; }
    
    0 讨论(0)
  • 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<int> 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<IEnumerable<int>, string>
        {
            public IntListToStringValueConverter() : base(le => ListToString(le), (s => StringToList(s)))
            {
    
            }
            public static string ListToString(IEnumerable<int> value)
            {
                if (value.IsEmptyCollection())
                {
                    return null;
                }
     
                return value.Join(',');
            }
    
            public static IEnumerable<int> 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<SomeClass>()
                .Property(e => e.Values)//Property
                .HasConversion(IntValueConverter);
    
        }
    

    Done!! IT should work

    0 讨论(0)
提交回复
热议问题