当前位置: 移动技术网 > IT编程>开发语言>.net > Entity Framework (EF) Core工具创建一对多和多对多的关系

Entity Framework (EF) Core工具创建一对多和多对多的关系

2018年12月28日  | 移动技术网IT编程  | 我要评论

克拉玛依招聘,皮带哥张吉勇,爱情公寓413

 一、 entirtyframework(ef)简介

       entirtyframework框架是一个轻量级的可扩展版本的流行实体框架数据访问技术,微软官方提供的orm工具让开发人员节省数据库访问的代码时间,将更多的时间放到业务逻辑层代码上。ef提供变更跟踪、唯一性约束、惰性加载、查询事物等。开发人员使用linq语言,对数据库操作如同操作object对象一样省事。

       ef有三种使用场景,1. 从数据库生成class(db first),2.由实体类生成数据库表结构(code first),3.  通过数据库可视化设计器设计数据库,同时生成实体类(model first)。

                                                

         ef架构如下:    

                                                                                                                                                                                        

      edm (实体数据模型):edm包括三个模型,概念模型、 映射和存储模型。

      概念模型 ︰ 概念模型包含模型类和它们之间的关系。独立于数据库表的设计。

      存储模型 ︰ 存储模型是数据库设计模型,包括表、 视图、 存储的过程和他们的关系和键。

      映射 ︰ 映射包含有关如何将概念模型映射到存储模型的信息。

      linq to entities ︰ linq to entities 是一种用于编写针对对象模型的查询的查询语言。它返回在概念模型中定义的实体。

      entity sql: entity sql 是另一种炉类似于l2e的言语,但相给l2e要复杂的多,所以开发人员不得不单独学习它。

      object services(对象服务):是数据库的访问入口,负责数据具体化,从客户端实体数据到数据库记录以及从数据库记录和实体数据的转换。

      entity client data provider:主要职责是将l2e或entity sql转换成数据库可以识别的sql查询语句,它使用ado.net通信向数据库发送数据可获取数据。

      ado.net data provider:使用标准的ado.net与数据库通信。

二、entirtyframeworkcore(ef core)

       entity framework core (ef core) 是在 2016 年首次发布的 ef6 的完全重写。 它附带于 nuget 包中,是 microsoft.entityframeworkcore 的主要组成部分。 ef core 是一种跨平台产品,可以在 .net core 或 .net framework 上运行。ef core 提供了在 ef6 中不会实现的新功能(如、以及 linq 查询中的混合客户端/数据库评估但由于它是一个新代码库,所以会缺少一些 ef6 中的功能。

       efcore与之前的ef基本类似,区别在于配置的时候有一些差异;支持db first和model first,广泛使用的code first模式;也不再支持lazyload。

       efcore的数据库访问技术使用之前请先安装microsoft.entityframeworkcore包

三、ef core使用db first

       数据库优先(db first)编码步骤如下:        

       1、新建数据库
       2、对模型实施反向工程
           scaffold-dbcontext [-connection] <string> [-provider] <string> [-outputdir <string>] [-context <string>]
           [-schemas <string>] [-tables <string>] [-dataannotations] [ -force] [-project <string>]
           [-startupproject <string>] [-environment <string>] [<commonparameters>]
       3、在项目中配置数据库连接字符串。

 四、ef core使用code first

        编码优先(code first),执行步骤如下:

        1、新建模型类
        2、新建dbcontext
        3、在项目中配置数据库连接字符串
        4、执行如下命令(数据库迁移): add-migration [类名],     update-database

       数据表级联,这里主要说一下级联删除

        1、外键属性可为null的级联删除时外键属性直接设置为 null即可

        2、外键属性不可为null级联删除时会引发异常,需要设置删除行为 deletebehavior ,deletebehavior 的类型如下表所示

            

 

        数据加载是需要重点掌握的,ef的关联实体加载有三种方式:lazy loading,eager loading,explicit loading,其中lazy loading和explicit loading都是延迟加载。 

        (一)lazy loading(惰性加载)使用的是动态代理,默认情况下,如果poco类满足以下两个条件,ef就使用lazy loading:

                  poco类是public且不为sealed。导航属性标记为virtual。

                 关闭lazy loading,可以将lazyloadingenabled设为false,如果导航属性没有标记为virtual,lazy loading也是不起作用的。                 

 1     /// <summary>
 2     /// 用户信息表
 3     /// </summary>
 4     public class user
 5     {
 6         /// <summary>
 7         /// 用户id
 8         /// </summary> 
 9         //[key]
10         //[databasegenerated(databasegeneratedoption.identity)]  //设置自增
11         public int userid { get; set; }
12         /// <summary>
13         /// 用户编码
14         /// </summary>
15         public string userno { get; set; }
16         /// <summary>
17         /// 用户名称
18         /// </summary>
19         public string username { get; set; }
20         /// <summary>
21         /// 用户电话
22         /// </summary>
23         public string telphone { get; set; }
24         /// <summary>
25         /// 备注
26         /// </summary>
27         public string remark { get; set; } 
28         public virtual  orginazation org { get; set; }
29         public virtual icollection<userandrole> roles { get; set; }
30     }
user实体类
 1 /// <summary>
 2     /// 角色信息表
 3     /// </summary>
 4     public class role
 5     {
 6         /// <summary>
 7         /// 角色id
 8         /// </summary>
 9         //[key]
10         //[databasegenerated(databasegeneratedoption.identity)]  //设置自增
11         public int roleid { get; set; }
12         /// <summary>
13         /// 角色编码
14         /// </summary>
15         public string roleno { get; set; }
16         /// <summary>
17         /// 角色名称
18         /// </summary>
19         public string rolename { get; set; }
20         /// <summary>
21         /// 备注
22         /// </summary>
23         public string remark { get; set; }
24         public virtual icollection<userandrole> users { get; set; }
25     }
role实体类
 1  /// <summary>
 2     /// 部门信息表
 3     /// </summary>
 4     public class orginazation
 5     {
 6         //private readonly ilazyloader _lazyloader;
 7 
 8         //public orginazation(ilazyloader lazyloader)
 9         //{
10         //    _lazyloader = lazyloader;
11         //}
12 
13         /// <summary>
14         /// 部门id
15         /// </summary>
16         [key]
17         [databasegenerated(databasegeneratedoption.identity)]  //设置自增
18         public int orgid { get; set; }
19         /// <summary>
20         /// 部门编码
21         /// </summary>
22         public string orgno { get; set; }
23         /// <summary>
24         /// 部门名称
25         /// </summary>
26         public string orgname { get; set; }
27         /// <summary>
28         /// 备注
29         /// </summary>
30         public string remark { get; set; }
31         public virtual icollection<user> users { get; set; }
32     }
orginazation实体类
userandrole

在.net core2.0及以上版本中使用惰性加载需要引用惰性加载代理包,ef core一般情况下使用惰性加载,因此为了避免报循环引用的异常需要设置referenceloophandling为ignore

install-package microsoft.entityframeworkcore.proxies 

startup.cs文件显示使用惰性加载

 public void configureservices(iservicecollection services)
        {
            services.configure<cookiepolicyoptions>(options =>
            {
                // this lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.checkconsentneeded = context => true;
                options.minimumsamesitepolicy = samesitemode.none;
            });

            services.adddbcontext<codefirstcontext>(options =>
            {
                //注入数据库
                options.usesqlserver(configuration.getconnectionstring("sqlserverconnstr")).tostring();
                //打开延迟加载代理的创建。
                options.uselazyloadingproxies();
            });
            services.addmvc().setcompatibilityversion(compatibilityversion.version_2_1).addjsonoptions(options =>
            {
                //由于使用了惰性加载,因此需要设置此参数避免报循坏引用的异常
                options.serializersettings.referenceloophandling = referenceloophandling.ignore;
            });
        }
startup.cs
 1     public class homecontroller : controller
 2     {
 3         private readonly codefirstcontext _dbcontext;
 4         public iconfiguration configuration { get; }
 5         string conn = string.empty;
 6         public homecontroller(codefirstcontext _context)
 7         {
 8             _dbcontext = _context; 
 9         }
10         public iactionresult index()
11         {
12             role role = new role
13             {
14                 roleno = "0001",
15                 rolename = "管理员角色",
16                 remark = "所有权限"
17             };
18             orginazation org = new orginazation
19             {
20                 orgno = "00001",
21                 orgname = "总公司",
22                 remark = "部门根节点"
23             };
24             user user = new user
25             {
26                 userno = "admin",
27                 username = "管理员",
28                 remark = "系统管理员",
29                 telphone="22342432",
30                 org = org
31             };
32             userandrole userandrolemodel = new userandrole
33             {
34                 role = role,
35                 user = user,
36                 roleid = role.roleid,
37                 userid = user.userid
38             };
39             user.roles.add(userandrolemodel);
40             role.users.add(userandrolemodel);
41             _dbcontext.roles.add(role);
42             _dbcontext.orginazations.add(org);
43             _dbcontext.users.add(user);
44             _dbcontext.userandroles.add(userandrolemodel);
45 
46 
47             _dbcontext.savechanges();
48 
49             //延迟加载
50             var orgs = _dbcontext.orginazations;
51             foreach (var usermodel in orgs.firstordefault().users)
52             {
53                 //删除部门用户
54                 _dbcontext.users.remove(usermodel);
55             }
56             _dbcontext.savechanges();
57             return view();
58         }
59 
60         public iactionresult about()
61         {
62             _dbcontext.roles.add(new role
63             {
64                 roleno = "role1",
65                 rolename = "rolename1",
66                 remark = "remark1"
67             }); 
68 
69             //删除用户,对应头像表里的数据也会被删除
70             var user = _dbcontext.users.first();
71             _dbcontext.users.remove(user);
72             _dbcontext.savechanges();
73 
74             viewdata["message"] = "your application description page.";
75 
76             return view();
77         }
78 
79         public iactionresult contact()
80         {
81             viewdata["message"] = "your contact page.";
82 
83             return view();
84         }
85 
86         public iactionresult privacy()
87         {
88             return view();
89         }
90 
91         [responsecache(duration = 0, location = responsecachelocation.none, nostore = true)]
92         public iactionresult error()
93         {
94             return view(new errorviewmodel { requestid = activity.current?.id ?? httpcontext.traceidentifier });
95         }
96     }
homecontroller
 1 /// <summary>
 2     /// code first编码上下文
 3     /// </summary>
 4     public class codefirstcontext : dbcontext
 5     { 
 6         public codefirstcontext(dbcontextoptions<codefirstcontext> conn)
 7            : base(conn)
 8         {
 9         } 
10         /// <summary>
11         /// 映射用户信息表
12         /// </summary>
13         public virtual dbset<user> users { get; set; }
14         /// <summary>
15         /// 映射部门信息表
16         /// </summary>
17         public virtual dbset<orginazation> orginazations { get; set; }
18         /// <summary>
19         /// 映射角色信息表
20         /// </summary>
21         public virtual dbset<role> roles { get; set; } 
22         /// <summary>
23         /// 用户角色信息表
24         /// </summary>
25         public virtual dbset<userandrole> userandroles { get; set; } 
26         protected override void onmodelcreating(modelbuilder modelbuilder)
27         { 
28             //用户
29             modelbuilder.entity<user>(entity =>
30                     {
31                         entity.totable("user");
32                         entity.property(e => e.username).isrequired().hasmaxlength(64);
33                         entity.property(e => e.userno).isrequired().hasmaxlength(64);
34                         entity.property(e => e.telphone).hasmaxlength(64);
35                         entity.property(e => e.remark).hasmaxlength(256);
36                         entity.hasone(u => u.org).withmany(r => r.users).ondelete(deletebehavior.setnull);
37                         
38                     });
39 
40             //角色
41             modelbuilder.entity<role>(entity =>
42             {
43                 entity.totable("role");
44                 entity.property(e => e.rolename).isrequired().hasmaxlength(64);
45                 entity.property(e => e.roleno).isrequired().hasmaxlength(64);
46                 entity.property(e => e.remark).hasmaxlength(256);                  
47             });
48 
49             //部门信息
50             modelbuilder.entity<orginazation>(entity =>
51             {
52                 entity.totable("orginazation"); 
53                 entity.property(e => e.orgno).isrequired().hasmaxlength(64);
54                 entity.property(e => e.orgname).isrequired().hasmaxlength(64);
55                 entity.property(e => e.remark).hasmaxlength(256);
56                 //多个用户对应一个部门
57                 entity.hasmany(u => u.users).withone(r => r.org).ondelete(deletebehavior.setnull);
58             });
59              
60             //用户角色信息表 
61             modelbuilder.entity<userandrole>(entity =>
62             {
63                 entity.totable("userandrole");
64                 entity.haskey(ua => new { ua.roleid, ua.userid });
65             });
66             modelbuilder.entity<userandrole>(entity =>
67             {
68                 entity.totable("userandrole");
69                 entity.hasone(u => u.role).withmany(r => r.users);
70             });
71             modelbuilder.entity<userandrole>(entity =>
72             {
73                 entity.totable("userandrole");
74                 entity.hasone(u => u.user).withmany(r => r.roles);
75             });
76         }
77     }    
codefirstcontext数据库上下文类

执行数据库迁移命令add-migration init22222结果如下:

更新数据库update-database,生成数据库表结果如下:

  至此、code first主要步骤完成了,通过code first正确创建了表之间一对多和多对多的关系,本实例中user和role是多对多的关系,user和orginazation是多对一的关系,

(二)eager loading(预加载)使用include方法关联预先加载的实体。在这里就不举例说明了。

(三)explicit loading(直接加载)使用entry方法,对于集合使用collection,单个实体则使用reference。在这里就不举例说明了。

 

以上是我对entity framework core的总结和使用,欢迎纠错!!! 

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网