无法映射属性“PropertyName”,因为它的类型为“List<decimal>”

Edu*_*scu 10 c# entity-framework-core

当我尝试使用 EntityFramework Core 创建数据库时遇到了这个问题:

无法映射属性“Rating.RatingScores”,因为它属于“List”类型,它不是受支持的原始类型或有效的实体类型。显式映射此属性,或使用 '[NotMapped]' 属性或使用 'OnModelCreating' 中的 'EntityTypeBuilder.Ignore' 忽略它。

这是课程:

public class Rating
{
    public int Id { get; set; }

    public List<decimal> RatingScores { get; set; }

    public decimal Score
    {
        set => Score = value;
        get => Math.Round(RatingScores.Sum() / RatingScores.Count, 1);
    }
}
Run Code Online (Sandbox Code Playgroud)

小智 14

如果 Rating 类有多个 RatingScores,则您具有一对多关系,并且 RatingScores 属性需要自己的表,因此您需要创建一个新类。

Class RatingScore 
{
  public int Id { get; set; }
  public decimal RtSc { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

然后 Rating 属性将如下所示:

public List<RatingScore> MyRatingScores { get; set; }
Run Code Online (Sandbox Code Playgroud)

但是,如果每个评级都有一个 RatingScore,则您的资产不应是一个集合。

public RatingScore MyRatingScore { get; Set; }
Run Code Online (Sandbox Code Playgroud)


Mou*_*mit 5

当你确实需要放置时multiple values in single column可以使用下面的方式

假设您只想为下面的类创建一张表

public class SomeClass
{
    public Guid ID { get; set; }
    public IEnumerable<int> Values { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

首先创建一个converter,它将控制.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==null || value.Count()==0)
            {
                return null;
            }
 
            return value.Join(',');
        }

        public static IEnumerable<int> StringToList(string value)
        {  
            if (value==null || value==string.Empty)
            {
                return null;
            }

            return value.Split(',').Select(i => Convert.ToInt32(i)); ; 
            
        }
    }
Run Code Online (Sandbox Code Playgroud)

并且DbContext应该有以下方法

 protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
         .....

        var IntValueConverter = new IntListToStringValueConverter();

        modelBuilder
            .Entity<SomeClass>()
            .Property(e => e.Values)//Property
            .HasConversion(IntValueConverter);

    }
Run Code Online (Sandbox Code Playgroud)

完毕!!IT 应该有效