没有模型和entity framework的ASP.NET MVC
我将ASP.Net应用程序迁移到ASP.NET MVC,我想避免使用模型和entity framework。 相反,我将使用方法来指导访问数据库。
我的问题是,这有可能吗? 两种方式之间的性能差异是什么?
谢谢。
我的问题是,这有可能吗?
当然这是可能的。 有一个小例外:没有模型的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; } }
然后定义您的数据访问合同(也就是您愿意对您的模型执行的操作):
public interface IPeopleRepository { IEnumerable Get(); ... other operations you want to perform with this model }
然后你可以实现你的实现:
public class ADOPeopleRepository: IPeopleRepository { public IEnumerable 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将是一块蛋糕,您需要做的就是编写几个视图模型和视图。
没有使用Entity Framework就好了,使用ADO.NET是可以接受的。 是的,这是可能的。
如果小心,您可以使您的数据访问代码比EF生成的代码更有效。 维护可能效率较低,因为EF为您做了很多工作。 请记住,维护成本非常昂贵。
但是,我不明白你为什么要避免模型而使用MVC。 我不建议采用这种方法。
上述就是C#学习教程:没有模型和entity framework的ASP.NET MVC分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/943288.html