Using asp net mvc what's the best practice for creating an action that allows to create a new project whose owner is the current logged user?
// Entities
class User {
[Key]
public int Id { get; set; }
public string FirstName { get; set; }
public string Username { get; set; }
public string Password { get; set; }
}
class Project {
[Key]
public int Id { get; set; }
public string Name { get; set; }
[Required]
public int OwnerId;
[ForeignKey("OwnerId")]
public User Owner? { get; set; }
}
// DTO / ModeView
class ProjectModelView {
public string Name;
}
class ProjectController : Controller {
private readonly ApplicationDbContext _context;
public ProjectController(ApplicationDbContext context) {
_context = context;
}
public IActionResult Create([Bind("Name")] Project project) {
return View();
}
// 1. Using the model directly
[HttpPost]
public IActionResult Create([Bind("Name")] Project project) {
project.Owner = Session.UserId;
if (ModelState.IsValid) {
_context.Projects.Add(project);
_context.SaveChanges();
return RedirectToAction(actionName: "Index");
}
return View(project);
}
// 2. Using a dto/model view (not sure if this is considerer a model view in this case)
[HttpPost]
public IActionResult Create(ProjectModelView project) {
if (ModelState.IsValid) {
_context.Projects.Add(new Project {
OwnerId = User,
Name = project.name
});
_context.SaveChanges();
return RedirectToAction(actionName: "Index");
}
return View(project);
}
}
I looked up the asp .net documentation and I couldn't find a correct answer.
Which is more "ASP like" and correct option? Is there better ways to do it? Also, is the dto a ViewModel in this case?