首页 > 解决方案 > 该属性属于接口类型(“IFormFile”)。如果是文件上传时在asp.net core中手动设置的导航属性

问题描述

我正在尝试通过视图模型上传文件,并在经过一些处理后将该模型保存在数据库中。模型(处理后保存模型)和文件上传都可以单独正常工作。但是,当我将它们组合在一个发布请求中时,它会与 IFormFile 属性发生冲突,并且会出现此错误。

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

这是我的控制器代码

public class ProfileController : Controller 
{

    private readonly ApplicationDbContext _context;
    private IWebHostEnvironment _env;

    public ProfileController(ApplicationDbContext context, IWebHostEnvironment env)
    {
        _context = context;
        _env = env;
    }
    
    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Registration([Bind("Id,Name,ProfileImage")] ProfileViewModel profileViewModel)
    {
        Profile profile = new Profile();
        profile.Name = profileViewModel.Name;
        //loading remaining properties of the model from ViewModel

        //uploading file....
        if (profileViewModel.ProfileImage != null)
        {
            var uploads = Path.Combine(_env.WebRootPath, "Uploads");
            var filePath = Path.Combine(uploads, profileViewModel.ProfileImage.FileName);

            profileViewModel.ProfileImage.CopyTo(new FileStream(filePath, FileMode.Create));
            profile.ProfileImage = profileViewModel.ProfileImage.FileName;
        }
        if (ModelState.IsValid)
        {
            _context.Add(profile);
            await _context.SaveChangesAsync();

            return RedirectToAction("Index", "Home");
         }
        
        return View(profileViewModel);
    }
}

ProfileViewModel 和 Profile 模型代码

public class AfghanViewModel
{
    [Key]
    public int Id { get; set; }
    [Required]
    public string Name { get; set; }

    [Display(Name = "Profile Image")]
    [Required]
    public IFormFile ProfileImage { get; set; }

    [Required]
    public string Email { get; set; }
    // other attributes are below...........
}
public class Profile
{
    [Key]
    public int Id { get; set; }
    public string Name { get; set; }
    public string ProfileImage { get; set; }
    ..........
}

查看文件代码

<form asp-action="Registration" enctype="multipart/form-data">
<div class="col-md-3 form-group">
     <label asp-for="ProfileImage" class="control-label"></label>
     <input asp-for="ProfileImage" class="form-control" />
     <span asp-validation-for="ProfileImage" class="text-danger"></span>
</div>
 .....
</form>

文件上传工作正常,但模型没有保存并在这行代码上产生上述错误 _context.Add(profile);

我在这个领域的不同答案中尝试了几件事,但没有一个有效。

提前致谢

标签: asp.net-mvcasp.net-corefile-upload

解决方案


我有同样的问题。尝试

 [NotMapped]
    public IFormFile ProfileImage { get; set; }

推荐阅读