【问题标题】:Inserting data using Linq C# with MVC 3 Architecture in asp.net在 asp.net 中使用带有 MVC 3 架构的 Linq C# 插入数据
【发布时间】:2013-08-24 02:40:31
【问题描述】:

我正在使用控制器插入数据,

SignUpcontroller.cs

[HttpPost]
public ActionResult Index(SignUpModel sm)
{

using(DataClassesDataContext dc= new DataClassesDataContext())
{
Dummytable dm= new Dummytable();
{
dm.Name=sm.password;
}
//then conncetion string and submit
}
}

和重定向

我的问题是,在控制器模块中编写此代码是否正确,或者我是否需要在模型模块中编写它,如果我需要在模型模块中编写它,那么如何定义设置器帮助我

【问题讨论】:

    标签: asp.net asp.net-mvc-3 linq


    【解决方案1】:

    为了让实现工作,我只是在控制器的强制转换的帮助下给类的内存提供接口

    [HttpPost]
    public ActionResult Index(SignUpModel sm)
    {
    ISignUpModel ISign= (ISignUpModel)this.sm;
    ISign.Insert(sm);
    }
    

    谢谢大家,因为你们,我学到了这个:)

    并且在SignUpModel.cs中,是正常的“接口命名为ISignUp with Insert方法”实现

    【讨论】:

      【解决方案2】:

      这在注册等重要数据存储/访问中并不常见。考虑使用网络安全工具,不要直接使用此类数据。或者改变你的意思来处理公共数据。

      【讨论】:

      • 我是 MVC 新手,我只是想知道我应该把代码放在哪里?
      【解决方案3】:

      第一个问题是你的DataAccessLayer 在哪里?

      所以更好的做法是在另一个类中编写代码来读取和写入数据库值。

      controller 仅适用于 UI 逻辑

      您可以使用Interface 来增加可重用性和单元测试。

      【讨论】:

      • 我用过DataClasses.dbml
      【解决方案4】:

      最好在数据访问层中移动所有数据访问代码。因此,只需将此代码放在一个单独的类中,您就可以从控制器中引用和调用。例如,您可以定义一个接口来定义不同的操作:

      public interface IRepository
      {
          void Insert(SignUpModel model);
      }
      

      然后有一个与您正在使用的数据访问技术(例如 EF)一起使用的特定实现:

      public class RepositoryEF : IRepository
      {
          public void Insert(SignUpModel model)
          {
              using(DataClassesDataContext dc= new DataClassesDataContext())
              {
                  Dummytable dm = new Dummytable();
                  dm.Name = sm.password;
              }
          }
      }
      

      下一步是让您的控制器将此存储库作为构造函数依赖项:

      public class SomeController : Controller
      {
          private readonly IRepository repo;
          public SomeController(IRepository repo)
          {
              this.repo = repo;
          }
      
          [HttpPost]
          public ActionResult Index(SignUpModel sm)
          {
              this.repo.Insert(sm);
      
              ...
          }
      }
      

      现在剩下的就是选择一些 DI 框架并连接依赖项。

      这样,您的控制器逻辑和数据访问层之间就有了清晰的分离。这将允许您对应用程序的各个层进行单独的单元测试。

      【讨论】:

      • 在signupmodel.cs中我写了getter setter?可以在该模块中包含更多类吗?
      • 您可以在单独的 .cs 文件中定义接口和实现。
      • 接口是必须的吗?
      • 插入问题:dc.Dummytables.InsertOnSubmit(dm);
      猜你喜欢
      • 2016-05-19
      • 2011-07-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-17
      • 2010-09-25
      • 2011-07-26
      • 2011-03-04
      相关资源
      最近更新 更多