简体   繁体   English

ASP.NET MVC - 在 POST/PUT(架构)上存储对象的最佳方式是什么

[英]ASP.NET MVC - What's the best way to store objects on POST/PUT (Architecture)

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?使用 asp net mvc 创建允许创建所有者是当前登录用户的新项目的操作的最佳实践是什么?

// 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.我查阅了 asp .net 文档,但找不到正确的答案。

Which is more "ASP like" and correct option?哪个更“像 ASP”和正确的选项? Is there better ways to do it?有更好的方法吗? Also, is the dto a ViewModel in this case?另外,在这种情况下 dto 是 ViewModel 吗?

I can suggest you this improvements, hope it helps:我可以建议您进行此改进,希望对您有所帮助:

  1. Do not inject your db context into controllers - it is bad practise.不要将您的数据库上下文注入控制器 - 这是不好的做法。 What if your controller's methods will contain a lot of logic?如果你的控制器的方法包含很多逻辑怎么办? And what if two controllers has similar methods with similar algorithm?如果两个控制器具有相似的算法和相似的方法怎么办? You can add MediatR library with commands and handlers, and in handlers you can use you db context logic.您可以使用命令和处理程序添加 MediatR 库,并且在处理程序中您可以使用数据库上下文逻辑。 Example: https://medium.com/dotnet-hub/use-mediatr-in-asp-net-or-asp-net-core-cqrs-and-mediator-in-dotnet-how-to-use-mediatr-cqrs-aspnetcore-5076e2f2880c示例: https ://medium.com/dotnet-hub/use-mediatr-in-asp-net-or-asp-net-core-cqrs-and-mediator-in-dotnet-how-to-use-mediatr- cqrs-aspnetcore-5076e2f2880c
  2. No dto is not view class, you should split domain objects and view objects, you can look to Mapper Example: https://code-maze.com/automapper-net-core/没有 dto 不是视图类,你应该拆分域对象和视图对象,你可以查看 Mapper 示例: https ://code-maze.com/automapper-net-core/
  3. About your question: Check the actor role: https://www.syncfusion.com/succinctly-free-ebooks/akka-net-succinctly/actors-in-asp-net-core关于您的问题:检查演员角色: https ://www.syncfusion.com/succinctly-free-ebooks/akka-net-succinctly/actors-in-asp-net-core

However I'm not sure that your question are still exists when you do a little refactoring from 1 and 2但是,当您从 1 和 2 进行一些重构时,我不确定您的问题是否仍然存在

I use the Repository/Service pattern , togeter with N-tier architecture .我使用Repository/Service pattern ,与N-tier architecture一起使用。

N-tier architecture looks like this N-tier architecture是这样的

ProjectName.Web/Server , depending if youre making like an mvc application , then its .Web , if just a web api , then .Server This is the main project with controllers, automapper, views etc. ProjectName.Web/Server ,取决于你是否像mvc application那样制作,然后是它的.Web ,如果只是一个web api ,然后是.Server这是带有controllers, automapper, views等的主要项目。

Then three class libraries projects然后是三个class libraries projects

ProjectName.Business , this projects is used to store most of the helper logic and diffrent kind of business logic for your application, also the DTOs or ViewModels ProjectName.Business ,该项目用于存储应用程序的大部分helper逻辑和不同类型的business logic ,以及DTOsViewModels

ProjectName.DataAccess , data access is the project with the direct connection to the database , this is the place where I use my repository folder with the context method, like put, get, post etc. Also the DbContext ProjectName.DataAccess ,数据访问是直接连接到database的项目,这是我使用我的repository foldercontext方法的地方,比如put, get, post等。还有DbContext

ProjectName.Models , this project is pretty simple, it is just used for all the entities/models you're going to use ProjectName.Models ,这个项目非常简单,它只用于您将要使用的所有entities/models

So how is all this connected?那么这一切是如何联系起来的呢? The projects need project references.项目需要project references.

This is how it will go .Models > .DataAccess > .Business > .Web/Server这就是它的运行方式.Models > .DataAccess > .Business > .Web/Server

It goes from the bottom to the top, with the Web/Server project as the top since this is the real application.它从底部到顶部, Web/Server project位于顶部,因为这是real application.

So how do I implement the repository pattern into the N-Tier architecture ?那么如何将repository pattern实现到N-Tier architecture中呢?

I Create a Repository folder in the .DataAccess project.我在.DataAccess project.中创建了一个Repository folder Inside the repository create the files, for exempel if you have a model and controller called EmployeeController.cs and Employee.cs Then inside the Repository folder , to keep it clean - create a sub folder, simply called Employee .在存储库中创建文件,例如,如果您有一个名为EmployeeController.csEmployee.cs的模型和controller 。然后在Repository folder中,为了保持干净 - 创建一个子文件夹,简称为Employee Inside the Employee folder , create 2 files.Employee folder中,创建 2 个文件。 EmployeeRepository.cs and IEmployeeRepository.cs Inside the EmployeeRepository you need a reference to IEmployeeRepository so your functions and methods will be available to other files. EmployeeRepository.csIEmployeeRepository.csEmployeeRepository中,您需要对IEmployeeRepository的引用,以便您的函数和方法可用于其他文件。 And then just create all the context logic in the repository files.然后只需在存储库文件中创建所有上下文逻辑。

To keep another layer between the .Web/Server project and the database, I Create a folder inside of the .Business project , called Service .为了在.Web/Server项目和数据库之间保留另一层,我在.Business project中创建了一个名为Service的文件夹。 This is the same principle as the Repository , create a sub folder called Employee , with EmployeeService.cs and IEmployeeService.cs , call all of the methods from the repository to the service, and then you call the service methods from the IEmployeeService to the EmployeeController inside of the .Web/Server project, using dependency injection .这和Repository的原理是一样的,创建一个子文件夹Employee ,里面有EmployeeService.csIEmployeeService.cs ,调用 repository 到 service 的所有方法,然后调用IEmployeeServiceEmployeeController的 service 方法在.Web/Server项目内部,使用dependency injection

And there you have it, complete isolation from the dbcontext in the controllers.就这样,与控制器中的 dbcontext 完全隔离。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在 Asp.Net MVC 中存储 Authorize 属性的用户列表的最佳方法是什么? - What is the best way to store Users list for a Authorize attribute in Asp.Net MVC? 从asp.net mvc 2应用程序将pdf文件存储在sql服务器中的最佳方法是什么? - what is the best way to store pdf files in sql server from an asp.net mvc 2 application? 在Asp.Net MVC 5中存储图像的最佳方法 - Best way to store images in Asp.Net MVC 5 存储ASP.NET 4.5 MVC用户数据的最佳方法 - Best way to store ASP.NET 4.5 MVC user data 在ASP.NET MVC解决方案中从我的域对象重构表示代码的最佳方法是什么? - What is the best way to refactor presentation code out of my domain objects in an ASP.NET MVC solution? ASP.NET MVC在post方法期间更新数据库对象的正确方法是什么 - ASP.NET MVC What is the proper way to update database objects during post methods 为ASP.NET MVC Intranet应用程序实施Windows身份验证的最佳方法是什么? - What's the best way to implement Windows Authentication for an ASP.NET MVC intranet application? ASP.NET MVC - 从视图中创建 Url 到 controller 动作的最佳方法是什么? - ASP.NET MVC - What's the best way to create a Url to controller action from within view? 为ASP.NET MVC项目设置数据访问的最佳方法是什么? - What's the best way to set up data access for an ASP.NET MVC project? 使用Twitter Bootstrap在ASP.NET MVC中调用模式对话框的最佳方法是什么? - What's the best way to call a modal dialog in ASP.NET MVC using Twitter Bootstrap?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM