【发布时间】:2020-07-24 11:48:23
【问题描述】:
我正在尝试通过视图模型上传文件,并在经过一些处理后将该模型保存在数据库中。模型(处理后保存模型)和文件上传都可以单独工作。但是,当我将它们组合在一个发布请求中时,它会与 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);
我在这个领域的不同答案中尝试了几件事,但没有一个有效。
提前致谢
【问题讨论】:
-
不要使用实体类型作为视图模型——除此之外还有很多原因(一个很好的示例,为什么“编辑用户”页面应该有两个明文“密码”和“确认密码” " 字段 - 但
User的实体类型将有一个散列的PasswordHash和PasswordHashSalt字段 - 你明白为什么现在不应该直接向用户公开实体模型了吗?)。 -
相反,为此视图定义一个单独的视图模型,并在视图模型和您的实体类型之间创建映射(例如,使用 AutoMapper 或手动)。
-
我不明白你的整个想法。你能更具体一点,让我做什么?
标签: asp.net-mvc asp.net-core file-upload