首页 > 解决方案 > 如何解决文件上传代码C#中的错误?

问题描述

我正在尝试将图像上传到服务器并保存它们,以便我可以在用户站点上使用它们,但我遇到了这个映射错误,需要帮助来解决这个问题。

我尝试将属性名称从字符串更改为,IFormFile但没有奏效。然后我再次将其更改为字符串并创建了另一个属性

public IFormFile Thumbnail 

但我得到一个模棱两可的错误来解决这个我将属性更改为

public IFormFile Thumbnailimg 

Bug 和 ShortVideo 也是如此。

模型.cs

using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;

namespace BuildShow.Models
{
    public partial class Assets
    {
        public int Id { get; set; }
        public int TypeFid { get; set; }
        public int CategoryFid { get; set; }
        public string Name { get; set; }
        public string Title { get; set; }
        public string ShortDescription { get; set; }
        public string LongDescription { get; set; }
        public string ArticleText { get; set; }
        public string Thumbnail { get; set; }
        public string Hero { get; set; }
        public string Bug { get; set; }
        public string ShortVideo { get; set; }
        public string VideoId { get; set; }
        public int TagFid { get; set; }
        public int ContributerFid { get; set; }
        public bool? Enabled { get; set; }
        public bool? Featured { get; set; }
        public bool? ShowOnHomePage { get; set; }
        public string SortOrder { get; set; }

        public virtual Categories CategoryF { get; set; }
        public virtual Contributor ContributerF { get; set; }
        public virtual Tags TagF { get; set; }
        public virtual AssetType TypeF { get; set; }


        public IFormFile Thumbnailimg { get; set; }
        public IFormFile Heroimg { get; set; }
        public IFormFile Bugimg { get; set; }
        public IFormFile ShortVideoup { get; set; }
    }
}

控制器.cs

if (id != assets.Id)
{
    return NotFound();
}

if (ModelState.IsValid)
{
    try
    {
        _context.Update(assets);
        await _context.SaveChangesAsync();
    }
    catch (DbUpdateConcurrencyException)
    {
        if (!AssetsExists(assets.Id))
        {
            return NotFound();
        }
        else
        {
            throw;
        }
    }

    return RedirectToAction(nameof(Index));
}

错误:

InvalidOperationException:属性“Assets.Thumbnailimg”属于接口类型(“IFormFile”)。如果它是导航属性,则通过将其转换为映射的实体类型手动配置此属性的关系,否则使用“OnModelCreating”中的 NotMappedAttribute 或“EntityTypeBuilder.Ignore”忽略该属性。

标签: asp.netasp.net-coreasp.net-mvc-5asp.net-core-mvcasp.net-core-3.0

解决方案


为了保存到您的数据库,您的模型需要反映您的表格。

您无法将接口类型保存到数据库

如果你不想在你的数据库中使用这个属性,你可以添加:

[NotMapped]

推荐阅读