zoukankan      html  css  js  c++  java
  • Entity Framework实例

    1、数据定义

    Book表

    using System;
    using System.Data.Objects;
    using System.Data.Objects.DataClasses;
    using System.Data.EntityClient;
    using System.ComponentModel;
    using System.Data.Entity;
    using System.ComponentModel.DataAnnotations;

    namespace EFTest.Models.Part2
    {
        [Table("Book")]
        public class Book
        {
            [Key]
            public int BookId { get; set;}
            public string BookName { get; set; }
            public int CatalogId { get; set; }

            public virtual Catalog catalog { get; set; }
        }


    }

    Catalog表

    using System;
    using System.Data.Objects;
    using System.Data.Objects.DataClasses;
    using System.Data.EntityClient;
    using System.ComponentModel;
    using System.Data.Entity;
    using System.ComponentModel.DataAnnotations;


    namespace EFTest.Models.Part2
    {
        [Table("Catalog")]
        public class Catalog
        {
            [Key]
            public int CatalogId { get; set; }
            public string Name { get; set; }

        }
    }

    2.数据访问层

    using System;
    using System.Data.Objects;
    using System.Data.Objects.DataClasses;
    using System.Data.EntityClient;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Data.Entity;

    namespace EFTest.Models.Part2
    {
       
       
        public partial class DbContextFactory : DbContext
        {
            public DbSet<Book> Books { get; set; }
            public DbSet<Catalog> Catalogs { get; set; } 
        }
    }

    web.config加入以下配置

      <connectionStrings>
        <add name="DbContextFactory"
    providerName="System.Data.SqlClient"
    connectionString="Server=(local);initial catalog=TestEF;user id=sa;password=abc123_;"/>

      </connectionStrings>

    数据增加、删除、修改

    Book book = new Book
    {
    BookName = "kenny",
    CatalogId = 3
    };
    using (var context = new DbContextFactory())
    {
    context.Books.Add(book);
    context.SaveChanges();//增加
                   

    book = context.Books.Find(2);
    context.Books.Remove(book);//删除
    context.SaveChanges();

    book = context.Books.Find(2);
    book.BookName = "ss";
    context.SaveChanges();//修改

    }

  • 相关阅读:
    Storm概念学习系列之storm出现的背景
    Storm概念学习系列之什么是实时流计算?
    Storm概念学习系列之storm-starter项目(完整版)(博主推荐)
    JAVA 毕业设计 辅导
    可视化的Redis数据库管理工具redis-desktop-manager的初步使用(图文详解)
    CentOS 7的安装详解
    GT-----如何做Android应用流量测试?
    性能测试开始前必知知识点
    【UI】自动化用例设计技巧
    国外免费接收短信验证码平台网站
  • 原文地址:https://www.cnblogs.com/kenny999/p/2300352.html
Copyright © 2011-2022 走看看