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

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

   首先在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; }
    }
}

 

posted @ 2016-10-26 17:15  Lucky-小王子  阅读(1865)  评论(0编辑  收藏  举报