asp.net-mvc - 该属性属于接口类型(“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);
我在这个领域的不同答案中尝试了几件事,但没有一个有效。
提前致谢
解决方案
我有同样的问题。尝试
[NotMapped]
public IFormFile ProfileImage { get; set; }
推荐阅读
- ruby-on-rails - 为具有连接关联的模型创建规范
- swift - NavigatorController 按钮不显示弹出警报
- unity3d - 在不使用 Player Prefs 等的情况下在场景之间进行对话的最简单方法
- php - 在单行中显示数组数据
- c# - 无法投射对象(DataRowView 到 DataGridRow)
- python - 在 python 中使用特定规则制作密码生成器
- python - 如何测试多个条件(经度和纬度)?
- fswatch - 限制 fswatch 运行的次数
- windows - 如何使用 Powershell 在 Docker RUN 命令中扩展参数?
- r - 使用 JSON 更新 HTML UI