Git.Framework 框架隨手記--ORM新增操作

賀臣發表於2014-05-06

  本篇主要記錄具體如何新增資料,廢話不多說,開始進入正文。

  一. 生成工程結構

    上一篇已經說到了如何生成工程結構,這裡在累述一次。

    1. 新建專案總體結構

      使用VS新建專案結構,分層結構可以隨意。我們使用的結構如下:

      

    2. 引入配置檔案相關

      Configs資料夾中的配置檔案,其目錄結構如下圖:

      

      以上幾個檔案為必須的,除了最下面的畫紅線的為自定義可以修改,具體配置項內容可以參考前面幾篇文章。然後再web.config定義如下配置:

<appSettings>
    <add key="DatabaseListFile" value="/Configs/Data/Database.config"/>
    <add key="DataCommandFile" value="/Configs/Data/DbCommandFiles.config"/>
    <add key="console" value="true"/>
    <add key="file" value="true"/>
    <add key="level" value="info"/>
    <add key="logpath" value="\Log\"/>
    <add key="logtype" value="Daily"/>
  </appSettings>

    3. 生成相應的程式碼

[TableAttribute(DbName = "JooShowGit", Name = "Admin", PrimaryKeyName = "ID", IsInternal = false)]
    public partial class AdminEntity : BaseEntity
    {
        public AdminEntity()
        {
        }

        [DataMapping(ColumnName = "ID", DbType = DbType.Int32, Length = 4, CanNull = false, DefaultValue = null, PrimaryKey = true, AutoIncrement = true, IsMap = true)]
        public Int32 ID { get; set; }

        public AdminEntity IncludeID(bool flag)
        {
            if (flag && !this.ColumnList.Contains("ID"))
            {
                this.ColumnList.Add("ID");
            }
            return this;
        }

        [DataMapping(ColumnName = "UserName", DbType = DbType.String, Length = 20, CanNull = false, DefaultValue = null, PrimaryKey = false, AutoIncrement = false, IsMap = true)]
        public string UserName { get; set; }

        public AdminEntity IncludeUserName(bool flag)
        {
            if (flag && !this.ColumnList.Contains("UserName"))
            {
                this.ColumnList.Add("UserName");
            }
            return this;
        }

        [DataMapping(ColumnName = "PassWord", DbType = DbType.String, Length = 50, CanNull = false, DefaultValue = null, PrimaryKey = false, AutoIncrement = false, IsMap = true)]
        public string PassWord { get; set; }

        public AdminEntity IncludePassWord(bool flag)
        {
            if (flag && !this.ColumnList.Contains("PassWord"))
            {
                this.ColumnList.Add("PassWord");
            }
            return this;
        }

        [DataMapping(ColumnName = "UserCode", DbType = DbType.String, Length = 40, CanNull = false, DefaultValue = null, PrimaryKey = false, AutoIncrement = false, IsMap = true)]
        public string UserCode { get; set; }

        public AdminEntity IncludeUserCode(bool flag)
        {
            if (flag && !this.ColumnList.Contains("UserCode"))
            {
                this.ColumnList.Add("UserCode");
            }
            return this;
        }

        [DataMapping(ColumnName = "RealName", DbType = DbType.String, Length = 40, CanNull = false, DefaultValue = null, PrimaryKey = false, AutoIncrement = false, IsMap = true)]
        public string RealName { get; set; }

        public AdminEntity IncludeRealName(bool flag)
        {
            if (flag && !this.ColumnList.Contains("RealName"))
            {
                this.ColumnList.Add("RealName");
            }
            return this;
        }

        [DataMapping(ColumnName = "Email", DbType = DbType.String, Length = 30, CanNull = true, DefaultValue = null, PrimaryKey = false, AutoIncrement = false, IsMap = true)]
        public string Email { get; set; }

        public AdminEntity IncludeEmail(bool flag)
        {
            if (flag && !this.ColumnList.Contains("Email"))
            {
                this.ColumnList.Add("Email");
            }
            return this;
        }

        [DataMapping(ColumnName = "Mobile", DbType = DbType.String, Length = 11, CanNull = true, DefaultValue = null, PrimaryKey = false, AutoIncrement = false, IsMap = true)]
        public string Mobile { get; set; }

        public AdminEntity IncludeMobile(bool flag)
        {
            if (flag && !this.ColumnList.Contains("Mobile"))
            {
                this.ColumnList.Add("Mobile");
            }
            return this;
        }

        [DataMapping(ColumnName = "Phone", DbType = DbType.String, Length = 20, CanNull = true, DefaultValue = null, PrimaryKey = false, AutoIncrement = false, IsMap = true)]
        public string Phone { get; set; }

        public AdminEntity IncludePhone(bool flag)
        {
            if (flag && !this.ColumnList.Contains("Phone"))
            {
                this.ColumnList.Add("Phone");
            }
            return this;
        }

        [DataMapping(ColumnName = "CreateTime", DbType = DbType.DateTime, Length = 8, CanNull = false, DefaultValue = null, PrimaryKey = false, AutoIncrement = false, IsMap = true)]
        public DateTime CreateTime { get; set; }

        public AdminEntity IncludeCreateTime(bool flag)
        {
            if (flag && !this.ColumnList.Contains("CreateTime"))
            {
                this.ColumnList.Add("CreateTime");
            }
            return this;
        }

        [DataMapping(ColumnName = "CreateIp", DbType = DbType.String, Length = 20, CanNull = true, DefaultValue = null, PrimaryKey = false, AutoIncrement = false, IsMap = true)]
        public string CreateIp { get; set; }

        public AdminEntity IncludeCreateIp(bool flag)
        {
            if (flag && !this.ColumnList.Contains("CreateIp"))
            {
                this.ColumnList.Add("CreateIp");
            }
            return this;
        }

        [DataMapping(ColumnName = "CreateUser", DbType = DbType.String, Length = 30, CanNull = true, DefaultValue = null, PrimaryKey = false, AutoIncrement = false, IsMap = true)]
        public string CreateUser { get; set; }

        public AdminEntity IncludeCreateUser(bool flag)
        {
            if (flag && !this.ColumnList.Contains("CreateUser"))
            {
                this.ColumnList.Add("CreateUser");
            }
            return this;
        }

        [DataMapping(ColumnName = "LoginCount", DbType = DbType.Int32, Length = 4, CanNull = false, DefaultValue = null, PrimaryKey = false, AutoIncrement = false, IsMap = true)]
        public Int32 LoginCount { get; set; }

        public AdminEntity IncludeLoginCount(bool flag)
        {
            if (flag && !this.ColumnList.Contains("LoginCount"))
            {
                this.ColumnList.Add("LoginCount");
            }
            return this;
        }

        [DataMapping(ColumnName = "Picture", DbType = DbType.String, Length = 60, CanNull = true, DefaultValue = null, PrimaryKey = false, AutoIncrement = false, IsMap = true)]
        public string Picture { get; set; }

        public AdminEntity IncludePicture(bool flag)
        {
            if (flag && !this.ColumnList.Contains("Picture"))
            {
                this.ColumnList.Add("Picture");
            }
            return this;
        }

        [DataMapping(ColumnName = "UpdateTime", DbType = DbType.DateTime, Length = 8, CanNull = false, DefaultValue = null, PrimaryKey = false, AutoIncrement = false, IsMap = true)]
        public DateTime UpdateTime { get; set; }

        public AdminEntity IncludeUpdateTime(bool flag)
        {
            if (flag && !this.ColumnList.Contains("UpdateTime"))
            {
                this.ColumnList.Add("UpdateTime");
            }
            return this;
        }

        [DataMapping(ColumnName = "IsDelete", DbType = DbType.Int16, Length = 2, CanNull = false, DefaultValue = null, PrimaryKey = false, AutoIncrement = false, IsMap = true)]
        public Int16 IsDelete { get; set; }

        public AdminEntity IncludeIsDelete(bool flag)
        {
            if (flag && !this.ColumnList.Contains("IsDelete"))
            {
                this.ColumnList.Add("IsDelete");
            }
            return this;
        }

        [DataMapping(ColumnName = "Status", DbType = DbType.Int16, Length = 2, CanNull = false, DefaultValue = null, PrimaryKey = false, AutoIncrement = false, IsMap = true)]
        public Int16 Status { get; set; }

        public AdminEntity IncludeStatus(bool flag)
        {
            if (flag && !this.ColumnList.Contains("Status"))
            {
                this.ColumnList.Add("Status");
            }
            return this;
        }

        [DataMapping(ColumnName = "DepartNum", DbType = DbType.String, Length = 20, CanNull = true, DefaultValue = null, PrimaryKey = false, AutoIncrement = false, IsMap = true)]
        public string DepartNum { get; set; }

        public AdminEntity IncludeDepartNum(bool flag)
        {
            if (flag && !this.ColumnList.Contains("DepartNum"))
            {
                this.ColumnList.Add("DepartNum");
            }
            return this;
        }

        [DataMapping(ColumnName = "ParentCode", DbType = DbType.String, Length = 40, CanNull = false, DefaultValue = null, PrimaryKey = false, AutoIncrement = false, IsMap = true)]
        public string ParentCode { get; set; }

        public AdminEntity IncludeParentCode(bool flag)
        {
            if (flag && !this.ColumnList.Contains("ParentCode"))
            {
                this.ColumnList.Add("ParentCode");
            }
            return this;
        }

        [DataMapping(ColumnName = "RoleNum", DbType = DbType.String, Length = 20, CanNull = false, DefaultValue = null, PrimaryKey = false, AutoIncrement = false, IsMap = true)]
        public string RoleNum { get; set; }

        public AdminEntity IncludeRoleNum(bool flag)
        {
            if (flag && !this.ColumnList.Contains("RoleNum"))
            {
                this.ColumnList.Add("RoleNum");
            }
            return this;
        }

        [DataMapping(ColumnName = "Remark", DbType = DbType.String, Length = 40, CanNull = true, DefaultValue = null, PrimaryKey = false, AutoIncrement = false, IsMap = true)]
        public string Remark { get; set; }

        public AdminEntity IncludeRemark(bool flag)
        {
            if (flag && !this.ColumnList.Contains("Remark"))
            {
                this.ColumnList.Add("Remark");
            }
            return this;
        }

    }
實體類AdminEntity
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using Git.Framework.ORM;
using Git.Storage.Entity.Base;

namespace Git.Storage.IDataAccess.Base
{
    public partial interface IAdmin : IDbHelper<AdminEntity>
    {
    }
}
資料訪問介面
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using Git.Framework.ORM;
using Git.Framework.MsSql;
using Git.Storage.Entity.Base;
using Git.Storage.IDataAccess.Base;

namespace Git.Storage.DataAccess.Base
{
    public partial class AdminDataAccess : DbHelper<AdminEntity>, IAdmin
    {
        public AdminDataAccess()
        {
        }

    }
}
資料訪問實現

 

  二. 使用IncludeAll() 方法新增

    可能大家覺得IncludeAll()方法很奇怪,這裡我們先看一個SQL語句

INSERT INTO [dbo].[OutStorage]([OrderNum],[OutType],[ProductType],[CusNum],[CusName],[Contact],[Phone],[Address],[ContractOrder],[Num],[Amount],[Weight],[SendDate],[Status],[IsDelete],[CreateTime],[CreateUser],[AuditUser],[AuditeTime],[PrintUser],[PrintTime],[Reason],[OperateType],[EquipmentNum],[EquipmentCode],[Remark]) VALUES(@OrderNum,@OutType,@ProductType,@CusNum,@CusName,@Contact,@Phone,@Address,@ContractOrder,@Num,@Amount,@Weight,@SendDate,@Status,@IsDelete,@CreateTime,@CreateUser,@AuditUser,@AuditeTime,@PrintUser,@PrintTime,@Reason,@OperateType,@EquipmentNum,@EquipmentCode,@Remark);

    SQL語句中有個INSERT INTO TABLE (ColName1,ColName2,ColName3,...) 插入語句包含了插入的欄位。在前面的對映過程中我們講到了每個欄位都有一個標識屬性用於對一個資料庫中的哪個欄位,IncludeAll() 方法就是用於包含類中的所有標識對應的資料庫欄位。

public int AddAdmin(AdminEntity entity)
{
            entity.IsDelete = (int)EIsDelete.NotDelete;
            entity.CreateTime = DateTime.Now;
            entity.ParentCode = "";
            entity.IncludeAll();
            int line = this.Admin.Add(entity);
            return line;
}
新增程式碼

    上面的程式碼中有一句就是恩提桶有.IncludeAll() 該方法就是用於包含這個類中所有的屬性欄位。

INSERT INTO [dbo].[Admin]([UserName],[PassWord],[UserCode],[RealName],[Email],[Mobile],[Phone],[CreateTime],[CreateIp],[CreateUser],[LoginCount],[Picture],[UpdateTime],[IsDelete],[Status],[DepartNum],[ParentCode],[RoleNum],[Remark]) VALUES(@UserName,@PassWord,@UserCode,@RealName,@Email,@Mobile,@Phone,@CreateTime,@CreateIp,@CreateUser,@LoginCount,@Picture,@UpdateTime,@IsDelete,@Status,@DepartNum,@ParentCode,@RoleNum,@Remark);

    上面的方法呼叫可以生成如上的SQL程式碼,這些欄位都是資料庫表中對應的欄位,使用下面的截圖程式測試效果如下:

最終通過呼叫Add方法,將資料插入到了資料庫,我們通過SQL管理器查詢可以看到插入的資料。

 

  三. Include 方法新增

    在系統中提供瞭如下幾個Include方法的過載和擴充套件

public static T Include<T, TKey>(this T entity, Expression<Func<T, TKey>> keySelector) where T : BaseEntity;
public static T Include<T>(this T entity, string propertyName) where T : BaseEntity;
public static T Include<T>(this T entity, string propertyName, string alias) where T : BaseEntity;

     以上三個方法都是擴充套件方法,第一個主要是用於對Lambda表示式的支援

entity.Include(a => new { a.DepartName,a.DicColumn,a.DepartNum,a.UserCode,a.UserName,a.PassWord });

    使用Lambda表示式可以更加方便的操作類的屬性,可以使用.操作。 如果將new{} 這個裡面指定所有的欄位就和IncludeAll()方法一樣。

    下面的兩個方法第一個用於直接包含欄位名稱,最後一個則是包含欄位名稱並且指定別人,這個和在查詢的時候有作用,查詢欄位指定別名。

public int AddAdmin(AdminEntity entity)
{
            entity.IsDelete = (int)EIsDelete.NotDelete;
            entity.CreateTime = DateTime.Now;
            entity.ParentCode = "";
            //entity.IncludeAll();
            entity.Include(a => new { a.DepartNum,a.UserCode,a.UserName,a.PassWord });
            int line = this.Admin.Add(entity);
            return line;
}
修改程式碼

    下面看看生成的SQL語句如下:

INSERT INTO [dbo].[Admin]([DepartNum],[UserCode],[UserName],[PassWord]) VALUES(@DepartNum,@UserCode,@UserName,@PassWord);

    並沒有包含所有的欄位資訊,通過對比應該可以明白Include方法的作用了。 但是這裡注意include 方法至少要包含一個欄位,否則程式異常。如果建有資料庫約束的欄位也要包含,比如不允許為NULL的,如果不包含預設做NULL處理,插入語句報錯。

 

  四. 插入集合

    這裡的插入集合要注意只能少量的插入,如果一次性幾萬是存在問題的。還是直接看程式碼

public override string Create(InStorageEntity entity, List<InStorDetailEntity> list)
        {
            using (TransactionScope ts = new TransactionScope())
            {
                int line = 0;
                entity.OrderNum = entity.OrderNum.IsEmpty() ? (new TNumProivder()).GetSwiftNum(typeof(InStorageEntity), 5) : entity.OrderNum;
                entity.IncludeAll();

                if (!list.IsNullOrEmpty())
                {
                    list.ForEach(a =>
                    {
                        a.IncludeAll();
                        a.OrderNum = entity.OrderNum;
                    });
                    entity.Num = list.Sum(q => q.Num);
                    entity.Amount = list.Sum(a => a.Amount);
                    line = this.InStorage.Add(entity);
                    line += this.InStorDetail.Add(list);
                }
                ts.Complete();
                return line > 0 ? EnumHelper.GetEnumDesc<EReturnStatus>(EReturnStatus.Success) : string.Empty;
            }
        }
批量INSERT

    方法this.InStorDetail.Add(list); 引數是一個List<T> 集合,呼叫該方法可以講多條資料插入到資料庫,但是在插入之前集合中的項都必須呼叫Include()或者IncludeAll() 用於包含插入哪些欄位。

 

  五. 新增方法彙總

int Add(List<T> list);
int Add(T entity);
int Add(List<T> list, bool isOpenTrans);
int Add(T entity, bool isOpenTrans);

    在系統框架中提供了以上四種新增的方法,下面兩個方法都多了一個引數就是在插入的時候是否啟用事務操作,true表示啟用,預設不啟用

 

相關文章