Nad*_*ali 7 c# entity-framework model asp.net-mvc-4
我将ASP.Net应用程序迁移到ASP.NET MVC,我想避免使用模型和实体框架.相反,我将使用方法来指导访问数据库.
我的问题是,这有可能吗?两种方式之间的性能差异是什么?
谢谢.
Dar*_*rov 28
我的问题是,这有可能吗?
当然这是可能的.除了一个小例外:没有模型的MVC不是MVC :-)它是VC,我个人从未听说过.无论是作为设计模式还是作为框架.听起来更像(WC :-))
两种方式之间的性能差异是什么?
你无法获得比原始ADO.NET更快的任何东西.所以,是的,与使用ORM相比,这将更快.
当然,您将需要编写更多代码,因为您仍然会有模型来映射查询的结果.不要认为您不使用EF的事实使您免于使用模型的责任.也不要以为你会使用DataTables.
所以基本上你会让你的数据层与这些模型一起工作.唯一的区别是实施.
我们来举个例子吧.
定义一个模型,该模型将代表您打算在应用程序中使用的业务实体:
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public DateTime Dob { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
然后定义您的数据访问合同(也就是您愿意使用模型执行的操作):
public interface IPeopleRepository
{
IEnumerable<Person> Get();
... other operations you want to perform with this model
}
Run Code Online (Sandbox Code Playgroud)
然后你可以实现你的实现:
public class ADOPeopleRepository: IPeopleRepository
{
public IEnumerable<Person> Get()
{
string connectionString = ...;
using (var conn = new SqlConnection(connectionString))
using (var cmd = conn.CreateCommand())
{
conn.Open();
cmd.CommandText = "SELECT id, name, age, dob FROM people";
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
yield return new Person
{
Id = reader.GetInt32(reader.GetOrdinal("id")),
Name = reader.GetString(reader.GetOrdinal("name")),
Age = reader.GetInt32(reader.GetOrdinal("age")),
Dob = reader.GetDateTime(reader.GetOrdinal("dob")),
};
}
}
}
}
... implementation of the other operations you want to perform with this model
}
Run Code Online (Sandbox Code Playgroud)
然后像往常一样,您可能有一个控制器来使用此存储库:
public class PeopleController: Controller
{
private readonly IPeopleRepository repository;
public PeopleController(IPeopleRepository repository)
{
this.repository = repository;
}
public ActionResult Index()
{
var people = this.repository.Get().ToList();
// Depending on the requirements of your view you might have
// other method calls here and collect a couple of your domain models
// that will get mapped and aggregated into a single view model
// that will be passed to your view
return View(people);
}
...
}
Run Code Online (Sandbox Code Playgroud)
现在剩下的就是将ADOPeopleRepository数据访问层的具体实现注册到您最喜欢的容器中.
看看事情是如何分层的.现在,如果您正确编写了当前的ASP.NET应用程序,那么您可能已经拥有了Models,接口和存储库实现.因此,将其迁移到ASP.NET MVC将是一块蛋糕,您需要做的就是编写几个视图模型和视图.
| 归档时间: |
|
| 查看次数: |
20583 次 |
| 最近记录: |