为什么.NET Core不需要Repository层

在刚开始接触ASP.NET时候,使用Repository层已经是一个根深蒂固的习惯了。但随着 .NET Core和Entity Framwork Core的发展以及多年实践,很多人都觉得Repository层其实没有必要,因为EF Core本身自带RepositoryUnit of Work属性。为什么现在不需要Repository层,以及去Repository层后是如何实现呢?

时间往前推到2013年左右,当时使用MVCEntity Framwork已经是主流,起先大概是这样的:
在这里插入图片描述
以上,DbContextController之间是强耦合,并且不方便单元测试,于是Repository层出现。
在这里插入图片描述
开发者在使用Repository层的时候发现了一些缺点,其中一个缺点是处理实体间关系时性能不佳。

比如有这样的两个类:

public class Student
{
    public Address Address{get;set;}
}
public class Address{}

当在repository层获取Student实例时,Entity Framwork默认使用Lazy Loading机制,就是只要程序代码不去获取StudentAddress属性就不会主动加载Student.Address属性。关于Lazy Loading举例如下:

using(var ctx = new SchoolDBEntities())
{
    IList<Student> stus = ctx.Students.ToList<Student>();
    Student std = stus[0];
    StudentAddress add = std.Address;
}

当获取Student集合的时候,背后会执行一次SQL语句,当获取StudentAddress属性的时候,背后会再次执行SQL语句。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值