当前位置: 代码迷 >> 综合 >> C#EntityFramework(EF基础)
  详细解决方案

C#EntityFramework(EF基础)

热度:80   发布时间:2023-12-01 13:13:17.0
C#EntityFramework(EF基础)

0.App.config 设置链接串

<connectionStrings><add name="con" connectionString="server=.;database=zhazhabade;uid=sa;pwd=sa" providerName="System.Data.SqlClient"/></connectionStrings>

1.设置上下文

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using EntityFramework;namespace EntityFramework_Zha
{
    class BookDemo3Context:DbContext    //上下文{
    public BookDemo3Context() : base("con")   //nameOrConnectionString{
    Database.SetInitializer<BookDemo3Context>(null);}protected override void OnModelCreating(DbModelBuilder modelBuilder){
    base.OnModelCreating(modelBuilder);modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();}public DbSet<BookType> BookTypes {
     get; set; }public DbSet<Book> Bools {
     get; set; }}
}

2.设置models

class BookType{
    public long Id {
     get; set; }[StringLength(20),Required]   //不允许为空public  string Name {
     get; set; }public DateTime? CreateTime {
     get; set; }}
class Book{
    public long Id {
     get; set; }public string Title {
     get; set; }public string Descr {
     get; set; }public DateTime CreateTime {
     get; set; }=DateTime.Now;[ForeignKey(nameof(BookType))]   //外键public long BookTypeId {
     get; set; }public BookType BookType {
     get; set; }}

3.接下来 配置migrations

(1)打开程序包管理控制台

enable-migrations   //激活后 会出现一个Migrations的文件夹 和configurations的配配置文件

configurations.cs

namespace EntityFramework.Migrations
{
    using System;using System.Data.Entity;using System.Data.Entity.Migrations;using System.Linq;internal sealed class Configuration : DbMigrationsConfiguration<EntityFramework_Zha.BookDemo3Context>{
    public Configuration(){
    AutomaticMigrationsEnabled = false;}protected override void Seed(EntityFramework_Zha.BookDemo3Context context){
    // This method will be called after migrating to the latest version.// You can use the DbSet<T>.AddOrUpdate() helper extension method// to avoid creating duplicate seed data.//这样可以在迁移的时候直接拆入//context.BookTypes.AddOrUpdate(new BookType{Name="散文"} );//context.BookTypes.AddOrUpdate(new BookType{Name="科幻"} );//context.BookTypes.AddOrUpdate(new BookType{Name="诗歌"} );//context.BookTypes.AddOrUpdate(new BookType{Name="儿童"} );}}
}

(2)打开程序包管理控制台

add-migrations createdb //后面那个是名字

(3)打开程序包管理控制台

update-database   //更新数据库

4.常用的操作

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using EntityFramework;namespace EntityFramework_Zha 
{ class Program{static void Main(string[] args){using (BookDemo3Context db = new BookDemo3Context()){db.Database.Log=(o) =>{Console.WriteLine(o.ToString());};//状态:数据取出:Unchanged(持久态)  Remove :deleted  保存:detached (游离态)  跟新:Modifiedvar type = new BookType() { Id = 3 };db.Entry(type).State = System.Data.Entity.EntityState.Unchanged;  //假设从数据库取出type.Name = "djdkj";db.Entry(type).State = System.Data.Entity.EntityState.Deleted;  //假设从数据库删除db.SaveChanges();//更新var type2 = new BookType(){Id = 2,Name = "zhazha"};db.Entry(type2).State = EntityState.Modified;  //假设更新db.SaveChanges();foreach (var item in db.BookTypes){Console.WriteLine(item.Name);}//查找的两种statevar item1 = db.BookTypes.AsNoTracking().FirstOrDefault(m => m.Name == "科幻");  //detachedvar item2 = db.BookTypes.FirstOrDefault(m => m.Name == "科幻");    //unchangeConsole.WriteLine($"state1:{db.Entry(item1).State},state1:{db.Entry(item2).State}" );}Console.ReadLine();}}
}