【问题标题】:The property 'PropertyName' could not be mapped, because it is of type 'List<string>'无法映射属性“PropertyName”,因为它的类型为“List<string>”
【发布时间】:2020-09-30 17:42:07
【问题描述】:

我正在尝试上传多张图片。所以我创建了一个模型来存储多个图像。我创建了一个属性public List&lt;string&gt; Photos { get; set; }然后当我为创建数据表进行迁移时,我收到了这个错误:


The property 'Shop.Photos' could not be mapped, because it is of type 'List<string>' which is not a supported primitive type or a valid entity type. Either explicitly map this property, or ignore it using the '[NotMapped]' attribute or by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating'.

这是我的模型

using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;

namespace ShopingCenter.Models
{
    public class Shop
    {
        public int Id { get; set; }

        [Required]
        [Display(Name = "product name")]
        public String Name { get; set; }
        [Required]
        public int Price { get; set; }


        public String Image { get; set; }

        public List<string> Photos { get; set; }

        [Required]
        public int Quantity { get; set; }

        [Required]
        public bool IsAvailable { get; set; }

        [Display(Name = "Category")]

        public int? CategoryTypeId { get; set; }

        [ForeignKey("CategoryTypeId")]
        public Category Category { get; set; }

        [Display(Name = "SubCategory")]

        public int? SubCategoryTypeId { get; set; }

        [ForeignKey("SubCategoryTypeId")]
        public SubCategory SubCategory { get; set; }
    }
}

我不明白问题出在哪里。我应该改变什么来上传多个文件?我是初学者。请帮忙。

【问题讨论】:

  • 字符串不是照片。字符串应该是什么样的?
  • @GertArnold 错误来自公共列表 Photos { get;放; } ...名称列表。
  • @GertArnold Gert...我看到您有 EF 的历史...并且想知道您是否可以提供一个好的教程资源...我很适合找到任何... TIA。

标签: c# asp.net-core entity-framework-core asp.net-core-mvc


【解决方案1】:

您需要 Shop.Photos 模型中的数据注释 [NotMapped]。 它不是原始类型。

 [NotMapped]
 public List<string> Photos { get; set; }

EF 无法将照片列表转换为数据库实体。

将多张图片存储到数据库中。

您需要一个类似以下的表格: 对此的数据注释不是 100% 确定的。

public class ShopImage
{
    [Key]
    ShopImageId {get,set}

    [ForeignKey("Shop")]
    public ShopId { get; set; }
    
    public byte[] Image { get; set; }
}

或者代替数据库中的实际图像...您存储名称。

【讨论】:

  • 究竟什么是“工作”?现在您拥有与数据库无关的属性 - 既不能存储也不能加载到数据库/从数据库加载。那为什么它在那里呢?
  • @lvan Stoev 你是对的。我刚才正在检查我的数据表。我找不到我的“照片”属性。!! .什么是解决方案。
  • "working" 表示 "migration" 和 "update" 成功。但我没有意识到 [notmapped] 的事实。
  • @ShaneWatson 您的目标是在数据库中存储图像列表吗?
  • @ChrisCatignani 是的。我想存储多个图像和节目。
【解决方案2】:

// 可能这可能有效

public string PhotosString { get; set; }

[NotMapped]
public List<string> Photos    
{
  get => PhotoString != null ? PhotosString.Split(',') : null;
  set => PhotosString = string.Join(",", value);
}

【讨论】:

    猜你喜欢
    • 2019-01-10
    • 1970-01-01
    • 2020-02-27
    • 1970-01-01
    • 2021-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多