• 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();//修改

    }

  • 相关阅读:
    cython教程
    CMake 教程
    Python的MySQLdb模块安装,连接,操作,增删改
    python异常处理try,except,else,finally,raise
    python中xrange和range的异同
    AttributeError: 'module' object has no attribute 'Thread'
    Java 中队列的使用
    INFORMIX 时间函数大全
    JMS的样例
    ACdream 1135(MST-最小生成树边上2个值,维护第一个最小的前提下让还有一个最小)
  • 原文地址:https://www.cnblogs.com/kenny999/p/2300352.html
Copyright © 2020-2023  润新知