请选择 进入手机版 | 继续访问电脑版
  • 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

关于C#的数据绑定,存取数据库实例详解(三)

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

这一节主要关于数据库的操作。

   首先在APP.config中添加connectionStrings 

<connectionStrings >
<add name="CIM.iFA.CIS.Infrastructure.Database.CIS210" providerName="System.Data.SqlClient" connectionString="Server=.\SQLEXPRESS;Initial Catalog=CIS20;Integrated Security=true;MultipleActiveResultSets=True"/>
</connectionStrings>

App.xaml.cs代码如下,据说创建数据库有四种方式:

策略一:数据库不存在时重新创建数据库

Database.SetInitializer<testContext>(new CreateDatabaseIfNotExists<testContext>());

策略二:每次启动应用程序时创建数据库

Database.SetInitializer<testContext>(new DropCreateDatabaseAlways<testContext>());

策略三:模型更改时重新创建数据库

Database.SetInitializer<testContext>(new DropCreateDatabaseIfModelChanges<testContext>());

策略四:从不创建数据库

Database.SetInitializer<testContext>(null);
比对了一下,暂时不知道我的是属于哪一种,反正不属于二和四,有待验证。应该属于模型变了重新创建吧,要不就是没有就创建,废话。
    public partial class App : Application
    {
        private Window mMainWin;
        private void Application_Startup(object sender, StartupEventArgs e)
        {
            Database.SetInitializer<CISDbContext>(new DropCreateDatabaseWithSeedData());
            using (var context = new CISDbContext())
            {
                context.Database.Initialize(true);
            }
            mMainWin = new MainWindow();
            this.mMainWin.Show ();
      }
    }

CISDbContext.cs代码如下:

   1) DbSet 建数据表

   2) CISDbContext():base()连接数据库的字符串。

   3)OnModelCreating 暂时还没用到。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.Core.Objects;
using System.Data.Entity.Core.EntityClient;
using SQL.DAL.Model;
using SQL.DAL;
using SQLtest.Model;

namespace CIS.DAL
{
    public class CISDbContext : DbContext, IDbContext
    {
        public DbSet<InlineToolModel> t_InlineToolModel { get; set; }

        public new IDbSet<TEntity> Set<TEntity>() where TEntity : class
        {
            return base.Set<TEntity>();
        }
        public CISDbContext(string connstr)
            : base(connstr)
        {
            var objectContext = (this as IObjectContextAdapter).ObjectContext;

            objectContext.CommandTimeout = 0;// 永不超时,单位秒
        }
        public CISDbContext()
            :base("name=CIM.iFA.CIS.Infrastructure.Database.CIS210")
        {
            var objectContext = (this as IObjectContextAdapter).ObjectContext;

            objectContext.CommandTimeout = 0;// 永不超时,单位秒
        }
        public ObjectContext ObjectContext
        {
            get
            {
                return ((this as IObjectContextAdapter).ObjectContext);
            }
        }
        public string ConnectionString
        {
            get
            {
                return (((EntityConnection)ObjectContext.Connection).StoreConnection.ConnectionString);
            }
        }
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
        }
    }
}

IDbContext.cs相关接口

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Entity;

namespace SQL.DAL
{
    public interface IDbContext
    {
        IDbSet<TEntity> Set<TEntity>() where TEntity : class;
        int SaveChanges();
        void Dispose();
    }
}

DropCreateDatabaseWithSeedData.cs,在数据库新建时,初始化数据。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Entity;
using SQL.DAL.Repository;
using SQL.DAL.Model;
using SQL.DAL;
using CIS.DAL;
using SQLtest.Model;

namespace SQL.DAL
{
    public class DropCreateDatabaseWithSeedData : DropCreateDatabaseIfModelChanges<CISDbContext>
    {
        protected override void Seed(CISDbContext context)
        {
            #region t_User内置
            Repository<InlineToolModel> oRepUser = new Repository<InlineToolModel>(context);
            oRepUser.Add(new InlineToolModel() {Name="AECVD"});
            #endregion
            
            context.SaveChanges();
            base.Seed(context);
        }
    }
}

Repository.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SQL.DAL.Model;
using System.Data.Entity;

namespace SQL.DAL.Repository
{
    public class Repository<TEntity> : IRepository<TEntity> where TEntity : class, IEntity
    {
        private IDbContext _context;

        public IDbContext Context
        {
            get { return _context; }
            set { _context = value; }
        }

        public Repository(IDbContext context)
        {
            _context = context;
        }

        private IDbSet<TEntity> DbSet
        {
            get
            {
                return _context.Set<TEntity>();
            }
        }

        public TEntity FindById(int Id)
        {
            return DbSet.SingleOrDefault(d => d.Id == Id);
        }

        public IQueryable<TEntity> GetAll()
        {
            return DbSet.AsQueryable();
        }

        public void Delete(TEntity entity)
        {
            DbSet.Remove(entity);
        }

        public void Delete(IQueryable<TEntity> entities)
        {
            foreach (TEntity entity in entities)
            {
                DbSet.Remove(entity);
            }
        }

        public void Add(TEntity entity)
        {
            DbSet.Add(entity);
        }

        public void Add(IQueryable<TEntity> entities)
        {
            foreach (TEntity entity in entities)
            {
                DbSet.Add(entity);
            }
        }

        public void Add(IEnumerable<TEntity> entities)
        {
            foreach (TEntity entity in entities)
            {
                DbSet.Add(entity);
            }
        }

        public TEntity Update(TEntity pEntity)
        {
            if (((DbContext)_context).Entry<TEntity>(pEntity).State == EntityState.Modified)
                _context.SaveChanges();
            return pEntity;
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (_context != null)
                {
                    _context.Dispose();
                    _context = null;
                }
            }
        }
    } 
}

IRepository.cs相关接口

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SQL.DAL.Model;

namespace SQL.DAL.Repository
{
    public interface IRepository<TEntity> : IDisposable where TEntity : IEntity
    {
        IQueryable<TEntity> GetAll();
        void Delete(TEntity entity);
        void Add(TEntity entity);
    }
}

IEntity.cs相关接口

using System;
namespace SQL.DAL.Model
{
    public interface IEntity
    {
        int Id { get; set; }
    }
}

 


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C#超简单自定义事件发布时间:2022-07-18
下一篇:
C#实现单例模式的几种方法发布时间:2022-07-18
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap