分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 代码编程

ASP.NET 之 EntityFramework实体框架搭建

发布时间:2023-09-06 01:40责任编辑:苏小强关键词:.NET
 

  前段时间接触了EntityFramework,对ORM框架也是有了初步的认识,现在对其进行一点小总结。

一、ORM简介

  对象关系映射(Object Relational Mapping,简称ORM)模式是一种为了解决面向对象与关系数据库存在的互不匹配的现象的技术。简单的说,ORM是通过使用描述对象和数据库之间映射的元数据,将程序中的对象自动持久化到关系数据库中。是不是还是不懂?那我们把ORM拆开来说:

O   创建简单的实体对象,也就是数据Model

R   关系数据库中数据表

M   把实体对象与关系数据库具体数据表关联起来,产生相应的SQL操作

  在对象中主要利用 特性 来标识主外键、字段长度、默认值等。

二、EntityFramework的安装

  1. 在解决方案处单击右键
  2. 管理解决方案的NuGet程序包
  3. 在搜索框中搜索EntityFramework
  4. 勾选要安装的项目
  5. 安装EF

三、EntityFramework的简单配置

  • 对Web.config中的连接数据库的字符串进行配置
     ?<connectionStrings> ???<add name="DefaultConnection" connectionString="server=.;database=OnLineExamDB;uid=sa;pwd=123456;" providerName="System.Data.SqlClient" /> ?</connectionStrings>

    server=.;代表为本地、OnLineExamDB为我连接的数据库的名称、uid跟pwd是连接数据库的用户密码

  • 配置Model层、主键要用[Key]进行标识并引用命名空间System.ComponentModel.DataAnnotations;
  • using System;using System.Collections.Generic;using System.ComponentModel.DataAnnotations;using System.Linq;using System.Text;using System.Threading.Tasks;namespace Model{ ???public class Class ???{ ???????[Key] ???????//主键要加上[Key],并引用命名空间System.ComponentModel.DataAnnotations; ???????public int ClassID { get; set; } ???????/// <summary> ???????/// 班级名称 ???????/// </summary> ???????public string ClassName { get; set; } ???????????}}

    在DAL数据层创建DBFactory并继承DbContext,配置Model实体与表的关系

    View Code
  • 在BLL业务层中创建StudentService,查询数据库数据

  FirstOrDefault为返回序列中的第一个元素,如果没有该元素就返回默认值。

  • namespace BLL{ ???public class StudentService ???{ ???????DBFactory dbFactory = new DBFactory(); ???????????????public Student GetStudent() ???????{ ???????????return dbFactory.StudentFactory.FirstOrDefault(); ???????} ???}}

    在Controller中配置

    using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Mvc;using BLL;using Model;using OnLineExam.Models;using System.Web.Security;namespace OnLineExam.Controllers{ ???public class UserInfoController : Controller ???{ ???????StudentService StudentService = new StudentService(); ???????public ActionResult Index() ???????{ ???????????//获取学生Model ???????????var student = StudentService.GetStudent(); ???????????//存入ViewData用于获取 ???????????ViewData["Student"] = student; ???????????return View(); ???????} ???}}
  • 添加视图
    @using Model;@{ ???var student = ViewData["Student"] as Student; ???Layout = null;}<!DOCTYPE html><html><head> ???<meta name="viewport" content="width=device-width" /> ???<title>Index</title></head><body> ???<div> ????????学生名称:@student.StudentName ???</div> ???<div> ???????学生编号:@student.StudentNumber ???</div></body></html>

结果显示:

这样一个使用EntityFramework的ORM框架就成功实现了。

ASP.NET 之 EntityFramework实体框架搭建

原文地址:https://www.cnblogs.com/cjm123/p/8387037.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved