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

    }

  • 相关阅读:
    微众银行面试小总结
    关于撑开父容器高度的小探讨
    2015年9月阿里校招前端工程师笔试题
    高性能JavaScript 重排与重绘
    高性能JavaScript DOM编程
    纯CSS3动画实现小黄人
    JS+css3实现图片画廊效果总结
    新游戏《机械险境》
    Twitter "fave"动画
    fragment 与 activity
  • 原文地址:https://www.cnblogs.com/kenny999/p/2300352.html
Copyright © 2011-2022 走看看