ASP.NET MVC-什么是将对象存储在Post/put(架构)上的最佳方法

发布于 2025-02-08 09:04:58 字数 1725 浏览 2 评论 0原文

使用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);
  }
}

我查找了ASP .NET文档,但找不到正确的答案。

哪个是更“像ASP”和正确的选项?有更好的方法吗?另外,在这种情况下,dto aviemodel是吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

浪漫人生路 2025-02-15 09:04:58

我使用存储库/服务模式,带有n-tier Architecture的togeter。

n-tier架构看起来像

projectname.web/server,具体取决于您是否像MVC Application一样,则其.web,如果只是Web API,则.Server
这是带有控制器,AutoMapper,Views等的主要项目。

,三个class Libraries Project

然后 helper逻辑和业务逻辑的逻辑类型,也是dtosviewmodels

projectName.dataAccess,数据访问是与database直接连接的项目,这是我将我的repository文件夹一起使用的地方上下文方法,例如put,get,wet,post等。

另外您将仅用于所有实体/模型您将要使用的

所有这些连接如何?
项目需要项目参考。

这就是它的发展
.models> .dataAccess> .business> .web/server

它从底部到顶部,web/server project作为顶部,因为这是真实应用程序。

那么,如何将存储库模式n-tier体系结构中实现?

我在.dataAccess项目中创建存储库文件夹
在存储库中创建文件,如果您有模型和Controller,则为exempel, nater amployeecontroller.cs and employee.cs
然后在存储库文件夹中,要保持清洁 - 创建一个sub文件夹,简单地称为雇员。在员工文件夹中,创建2个文件。
lospereeerepository.csiemployeerepository.cs
loasheeerepository中,您需要引用iemployeeerepository,因此您的功能和方法将可用于其他文件。
然后只需在存储库文件中创建所有上下文逻辑即可。

要在.web/Server项目和数据库之间保留另一层,我在.business Project的内部创建一个文件夹,称为Service。这是与repository的原理相同的原理,创建一个名为雇员的子文件夹,使用employservice.csiemployeeservice.cs代码>,将所有方法从存储库调用到服务,然后您将服务方法从iemployeeService调用applyeecontroller.web> .web /server项目,使用依赖项注入

在那里,您可以从控制器中的DBContext完全隔离。

I use the Repository/Service pattern, togeter with N-tier architecture.

N-tier architecture looks like this

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.

Then three 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.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.Models, this project is pretty simple, it is just used for all the entities/models you're going to use

So how is all this connected?
The projects need project references.

This is how it will go
.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.

So how do I implement the repository pattern into the N-Tier architecture?

I Create a Repository folder in the .DataAccess project.
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. Inside the Employee folder, create 2 files.
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.
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. 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.

And there you have it, complete isolation from the dbcontext in the controllers.

浮华 2025-02-15 09:04:58

我可以建议您进行此改进,希望它有所帮助:

  1. 不要将DB上下文注入控制器 - 这是不好的做法。如果您的控制器的方法包含很多逻辑怎么办?如果两个控制器具有类似算法的类似方法,该怎么办?您可以将MediaTR库与命令和处理程序添加,在处理程序中,您可以使用DB上下文逻辑。
    示例: https://medium.com/dotnet-hub/use-mediath-mediath-mediatr--------------和介绍者中的dotnet-how-to-mediatr-cqrs-aspnetcore-5076e2f2880c
  2. no dto no dto不视图类别,您应该拆分域对象并查看对象,您可以查看映射器
    示例: https://code-maze/automapper-net-net-core/
  3. 关于您的问题:
    Check the actor role: https ://www.syncfusion.com/succinctly-free-ebooks/akka-net-succinctly/actors-inactors-in--asp-net-core

但是,我不确定当您进行时,您的问题仍然存在1和2的重构很少

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.
    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
  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/
  3. About your question:
    Check the actor role: 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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文