我要将ASP.Net应用程序迁移到ASP.NET MVC,我想避免使用模型和实体框架。相反,我将使用方法来指导访问数据库。
我的问题是,这有可能吗?两种方式之间的性能差异是什么?
感谢。
答案 0 :(得分: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; }
}
然后定义您的数据访问合同(a.k.a您愿意对您的模型执行的操作):
public interface IPeopleRepository
{
IEnumerable<Person> Get();
... other operations you want to perform with this model
}
那么你可以实现你的实现:
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
}
然后像往常一样,您可能有一个控制器来使用此存储库:
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);
}
...
}
现在剩下的就是将您的数据访问层的ADOPeopleRepository
具体实现注册到您最喜欢的容器中。
了解事情是如何分层的。现在,如果您正确编写了当前的ASP.NET应用程序,那么您可能已经拥有了Models,接口和存储库实现。因此,将其迁移到ASP.NET MVC将是一块蛋糕,您需要做的就是编写几个视图模型和视图。
答案 1 :(得分:2)
没有使用Entity Framework很好,使用ADO.NET是可以接受的。是的,这是可能的。
如果小心,您可以使您的数据访问代码比EF生成的代码更有效。维护可能效率较低,因为EF为您做了很多工作。请记住,维护成本非常昂贵。
但是,我不明白你为什么要避开模型然后使用MVC。我不推荐这种做法。