{%if (table.Type == DbTableType.StoreProcedure) {
	print("return;");
	return rTn;
 }
 %}using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Newtonsoft.Json;
using FreeSql;
using FreeSql.DataAnnotations;
{%
var dbf = dbfirst as FreeSql.IDbFirst;
var cols = (table.Columns as List<DbColumnInfo>);
var pks = (table.Primarys as List<DbColumnInfo>);
var fks = (table.Foreigns as List<DbForeignInfo>);

Func<string, string> UString = stra => stra.Substring(0, 1).ToUpper() + stra.Substring(1);
Func<DbColumnInfo, string> GetCsType = cola3 => {
	return dbf.GetCsType(cola3);
};
Func<DbForeignInfo, string> GetFkObjectName = fkx => {
	var eqfks = fks.Where(fk22a => fk22a.ReferencedTable.Name == fkx.ReferencedTable.Name);
	if (eqfks.Count() == 1) return "Obj_" + fkx.ReferencedTable.Name;
	var fkretname = fkx.Columns[0].Name;
	if (fkretname.EndsWith(fkx.ReferencedColumns[0].Name, StringComparison.CurrentCultureIgnoreCase)) fkretname = fkretname.Substring(0, fkretname.Length - fkx.ReferencedColumns[0].Name.Length).TrimEnd('_');
	if (fkretname.EndsWith(fkx.ReferencedTable.Name, StringComparison.CurrentCultureIgnoreCase)) fkretname = fkretname.Substring(0, fkretname.Length - fkx.ReferencedTable.Name.Length).TrimEnd('_');
	if (fkretname.StartsWith(fkx.ReferencedTable.Name, StringComparison.CurrentCultureIgnoreCase)) fkretname = fkretname.Substring(fkx.ReferencedTable.Name.Length).TrimStart('_');
	return "Obj_" + fkx.ReferencedTable.Name + (string.IsNullOrEmpty(fkretname) ? "" : ("_" + fkretname));
};

%}
namespace test.Model {

	[JsonObject(MemberSerialization.OptIn), Table(Name = "{#!string.IsNullOrEmpty(table.Schema) ? table.Schema + "." : ""}{#table.Name}"{if cols.Where(cola003 => cola003.Name.ToLower() == "is_deleted" || cola003.Name.ToLower() == "isdeleted").Any()}, SelectFilter = "a.IsDeleted = 1"{/if})]
	public partial class {#UString(table.Name)} {{for col,index in table.Columns}{%
			var findfks = fks.Where(fkaa => fkaa.Columns.Where(fkaac1 => fkaac1.Name == col.Name).Any());
		%}{if findfks.Any() == false}
		{if string.IsNullOrEmpty(col.Coment) == false}/// <summary>
		/// {#col.Coment.Replace("\r\n", "\n").Replace("\n", "\r\n		/// ")}
		/// </summary>{/if}
		[JsonProperty, Column(Name = "{#col.Name}", DbType = "{#col.DbTypeTextFull}"{if col.IsPrimary == true}, IsPrimary = true{/if}{if col.IsIdentity == true}, IsIdentity = true{/if}{if col.IsNullable == true}, IsNullable = true{/if})]
		public {#GetCsType(col)} {#UString(col.Name)} { get; set; }
		{else}
		private {#GetCsType(col)} _{#UString(col.Name)};
		{if string.IsNullOrEmpty(col.Coment) == false}/// <summary>
		/// {#col.Coment.Replace("\r\n", "\n").Replace("\n", "\r\n		/// ")}
		/// </summary>{/if}
		[JsonProperty, Column(Name = "{#col.Name}", DbType = "{#col.DbTypeTextFull}"{if col.IsPrimary == true}, IsPrimary = true{/if}{if col.IsIdentity == true}, IsIdentity = true{/if}{if col.IsNullable == true}, IsNullable = true{/if})]
		public {#GetCsType(col)} {#UString(col.Name)} { get => _{#UString(col.Name)}; set {
			if (_{#UString(col.Name)} == value) return;
			_{#UString(col.Name)} = value;{for fkcok2 in findfks}
			{#GetFkObjectName(fkcok2)} = null;{/for}
		} }
		{/if}{/for}{for fk in fks}
		public {#UString(fk.ReferencedTable.Name)} {#GetFkObjectName(fk)} { get; set; }
		{/for}
		internal static IFreeSql freesql => Const.sqlserver;
		public static ISelect<{#UString(table.Name)}> Select => freesql.Select<{#UString(table.Name)}>();
{if (table.Uniques.Count > 0)}
		public static int ItemCacheTimeout = 180;{for uk001 in table.Uniques}{%

		string parms = string.Empty;
		string parmsByWhereLambda = string.Empty;
		string parmsBy = "By";
		string parmsNodeTypeUpdateCacheRemove = string.Empty;
		foreach (var uk001col in uk001) {
			string getcstype = GetCsType(uk001col);
			parms += getcstype.Replace("?", "") + " " + UString(uk001col.Name) + ", ";
			parmsByWhereLambda += "a." + UString(uk001col.Name) + " == " + UString(uk001col.Name) + " && ";
			parmsBy += UString(uk001col.Name) + "And";
			parmsNodeTypeUpdateCacheRemove += "item." + UString(uk001col.Name) + ", \"_,_\", ";
		}
		parms = parms.Substring(0, parms.Length - 2);
		parmsByWhereLambda = parmsByWhereLambda.Substring(0, parmsByWhereLambda.Length - 4);
		parmsBy = parmsBy.Substring(0, parmsBy.Length - 3);
		parmsNodeTypeUpdateCacheRemove = parmsNodeTypeUpdateCacheRemove.Substring(0, parmsNodeTypeUpdateCacheRemove.Length - 9);
		%}
		public static {#UString(table.Name)} GetItem{#uk001[0].IsPrimary ? string.Empty : parmsBy}({#parms}) => Select.Where(a => {#parmsByWhereLambda}).Caching(ItemCacheTimeout, string.Concat("test:{#table.Name}{#uk001[0].IsPrimary ? string.Empty : parmsBy}:", {#parmsNodeTypeUpdateCacheRemove.Replace("item.", "")})).ToOne();{/for}
{for uk001 in table.Uniques}{%

		string parms = string.Empty;
		string parmsByWhereLambda = string.Empty;
		string parmsNewItem = string.Empty;
		string parmsBy = "By";
		string parmsNoneType = string.Empty;
		foreach (var uk001col in uk001) {
			string getcstype = GetCsType(uk001col);
			parms += getcstype.Replace("?", "") + " " + UString(uk001col.Name) + ", ";
			parmsByWhereLambda += "a." + UString(uk001col.Name) + " == " + UString(uk001col.Name) + " && ";
			parmsNewItem += UString(uk001col.Name) + " = " + UString(uk001col.Name) + ", ";
			parmsBy += UString(uk001col.Name) + "And";
			parmsNoneType += UString(uk001col.Name) + ", ";
		}
		parms = parms.Substring(0, parms.Length - 2);
		parmsByWhereLambda = parmsByWhereLambda.Substring(0, parmsByWhereLambda.Length - 4);
		parmsNewItem = parmsNewItem.Substring(0, parmsNewItem.Length - 2);
		parmsBy = parmsBy.Substring(0, parmsBy.Length - 3);
		parmsNoneType = parmsNoneType.Substring(0, parmsNoneType.Length - 2);
		%}
		public static long Delete{#uk001[0].IsPrimary ? string.Empty : parmsBy}({#parms}) {
			var affrows = freesql.Delete<{#UString(table.Name)}>().Where(a => {#parmsByWhereLambda}).ExecuteAffrows();{if table.Uniques.Count > 1}
			if (ItemCacheTimeout > 0) RemoveCache(GetItem{#uk001[0].IsPrimary ? string.Empty : parmsBy}({#parmsNoneType}));{else}
			if (ItemCacheTimeout > 0) RemoveCache(new {#UString(table.Name)} { {#parmsNewItem} });{/if}
			return affrows;
		}{/for}
{for fkcoldel in fks}{%
		string parms = string.Empty;
		string parmsBy = "By";
		string parmsByWhereLambda = string.Empty;
		foreach( var fkcoldelcol in fkcoldel.Columns) {
			string getcstype = GetCsType(fkcoldelcol);
			parms += getcstype.Replace("?", "") + " " + UString(fkcoldelcol.Name) + ", ";
			parmsBy += UString(fkcoldelcol.Name) + "And";
			parmsByWhereLambda += "a." + UString(fkcoldelcol.Name) + " == " + UString(fkcoldelcol.Name) + " && ";
		}
		parms = parms.Substring(0, parms.Length - 2);
		parmsBy = parmsBy.Substring(0, parmsBy.Length - 3);
		parmsByWhereLambda = parmsByWhereLambda.Substring(0, parmsByWhereLambda.Length - 4);
		%}
		public static long DeleteBy{#parmsBy}({#parms}) {
			return freesql.Delete<{#UString(table.Name)}>().Where(a => {#parmsByWhereLambda}).ExecuteAffrows(); //删除缓存
		}
{/for}{% string redisRemoveCode = string.Empty; %}{for uk001 in table.Uniques}{%

		string parmsBy = "By";
		string parmsNodeTypeUpdateCacheRemove = string.Empty;
		foreach (var uk001col in uk001) {
			parmsBy += UString(uk001col.Name) + "And";
			parmsNodeTypeUpdateCacheRemove += "item." + UString(uk001col.Name) + ", \"_,_\", ";
		}
		parmsBy = parmsBy.Substring(0, parmsBy.Length - 3);
		parmsNodeTypeUpdateCacheRemove = parmsNodeTypeUpdateCacheRemove.Substring(0, parmsNodeTypeUpdateCacheRemove.Length - 9);
		redisRemoveCode += $@"
				keys[keysIdx++] = string.Concat(""test:{table.Name}{(uk001[0].IsPrimary ? string.Empty : parmsBy)}:"", {parmsNodeTypeUpdateCacheRemove});";
		%}{/for}
		internal static void RemoveCache({#UString(table.Name)} item) => RemoveCache(item == null ? null : new [] { item });
		internal static void RemoveCache(IEnumerable<{#UString(table.Name)}> items) {
			if (ItemCacheTimeout <= 0 || items == null || items.Any() == false) return;
			var keys = new string[items.Count() * {#table.Uniques.Count}];
			var keysIdx = 0;
			foreach (var item in items) {{#redisRemoveCode}
			}
			if (freesql.Ado.TransactionCurrentThread != null) freesql.Ado.TransactionPreRemoveCache(keys);
			else freesql.Cache.Remove(keys);
		}
{if (table.Columns.Count < 100)}{%
		string CsParam3 = string.Empty;
		string CsParamNoType3 = string.Empty;
		string parms = string.Empty;
		string parmsByWhereLambda = string.Empty;
		string parmsNewItem = string.Empty;
		string parmsBy = "By";
		string parmsNoneType = string.Empty;
		var idens = 0;
		var idensCol = table.Columns[0];
		foreach (var uk001col in table.Columns) {
			string getcstype = GetCsType(uk001col);
			parms += getcstype.Replace("?", "") + " " + UString(uk001col.Name) + ", ";
			if (uk001col.IsPrimary)
				parmsByWhereLambda += "a." + UString(uk001col.Name) + " == " + UString(uk001col.Name) + " && ";
			parmsNewItem += UString(uk001col.Name) + " = " + UString(uk001col.Name) + ", ";
			parmsBy += UString(uk001col.Name) + "And";
			parmsNoneType += UString(uk001col.Name) + ", ";
			if (uk001col.IsIdentity) {
				idens++;
				idensCol = uk001col;
			} else {
				if (getcstype.StartsWith("DateTime") && (uk001col.Name.ToLower() == "create_time" || uk001col.Name.ToLower() == "update_time" || uk001col.Name.ToLower() == "createtime" || uk001col.Name.ToLower() == "updatetime") ||
					getcstype == "bool?" && (uk001col.Name.ToLower() == "is_deleted" || uk001col.Name.ToLower() == "isdeleted")) {

				} else {
					CsParam3 += getcstype + " " + UString(uk001col.Name) + ", ";
					CsParamNoType3 += string.Format("\r\n				{0} = {0}, ", UString(uk001col.Name));
				}
			}
		}
		parms = parms.Substring(0, parms.Length - 2);
		if (parmsByWhereLambda.Length > 0) parmsByWhereLambda = parmsByWhereLambda.Substring(0, parmsByWhereLambda.Length - 4);
		parmsNewItem = parmsNewItem.Substring(0, parmsNewItem.Length - 2);
		parmsBy = parmsBy.Substring(0, parmsBy.Length - 3);
		parmsNoneType = parmsNoneType.Substring(0, parmsNoneType.Length - 2);
		if (CsParam3.Length > 0) CsParam3 = CsParam3.Substring(0, CsParam3.Length - 2);
		if (CsParamNoType3.Length > 0) CsParamNoType3 = CsParamNoType3.Substring(0, CsParamNoType3.Length - 2);
		%}{if idens > 0}
		public static {#GetCsType(idensCol)} Insert({#UString(table.Name)} item) {
			item.{#UString(idensCol.Name)} = ({#GetCsType(idensCol)})freesql.Insert<{#UString(table.Name)}>().AppendData(item).ExecuteIdentity();
			if (ItemCacheTimeout > 0) RemoveCache(item);
			return item.{#UString(idensCol.Name)};
		}{else}
		public static void Insert({#UString(table.Name)} item) {
			if (ItemCacheTimeout > 0) RemoveCache(item);
			freesql.Insert<{#UString(table.Name)}>().AppendData(item).ExecuteAffrows();
		}
		public static long Insert(IEnumerable<{#UString(table.Name)}> items) {
			if (ItemCacheTimeout > 0) RemoveCache(items);
			return freesql.Insert<{#UString(table.Name)}>().AppendData(items).ExecuteAffrows();
		}{/if}
		{if CsParamNoType3.Split('=').Length <= 5}{if idens > 0}
		public static {#GetCsType(idensCol)} Insert({#CsParam3}) {
			var item = new {#UString(table.Name)} {{#CsParamNoType3}};
			item.{#UString(idensCol.Name)} = ({#GetCsType(idensCol)})freesql.Insert<{#UString(table.Name)}>().AppendData(new {#UString(table.Name)} {{#CsParamNoType3}}).ExecuteIdentity();
			if (ItemCacheTimeout > 0) RemoveCache(item);
			return item.{#UString(idensCol.Name)};
		}{else}
		public static {#UString(table.Name)} Insert({#CsParam3}) {
			var item = new {#UString(table.Name)} {{#CsParamNoType3}};
			freesql.Insert<{#UString(table.Name)}>().AppendData(item).ExecuteAffrows();
			if (ItemCacheTimeout > 0) RemoveCache(item);
			return item;
		}{/if}{/if}
		public static long Update({#UString(table.Name)} item) {
			if (ItemCacheTimeout > 0) RemoveCache(item);
			return freesql.Update<{#UString(table.Name)}>().SetSource(item).ExecuteAffrows();
		}
		public static long Update(IEnumerable<{#UString(table.Name)}> items) {
			if (ItemCacheTimeout > 0) RemoveCache(items);
			return freesql.Update<{#UString(table.Name)}>().SetSource(items).ExecuteAffrows();
		}
		/// <summary>
		/// 指定字段更新
		/// </summary>
		public IUpdate<{#UString(table.Name)}> UpdateDiy => freesql.Update<{#UString(table.Name)}>().Where(a => {#parmsByWhereLambda});
		/// <summary>
		/// {if pks.Count > 0}保存或添加，如果主键有值则尝试 Update，如果影响的行为 0 则尝试 Insert{else}添加{/if}
		/// </summary>
		public void Save() {{if pks.Count > 0}
			if ({#string.Join(" && ", pks.Select(pkssa => "this." + UString(pkssa.Name) + " != default(" + GetCsType(pkssa) + ")"))}) {
				var affrows = freesql.Update<{#UString(table.Name)}>().Where(a => {#parmsByWhereLambda}).ExecuteAffrows();
				if (affrows > 0) return;
			}{/if}
			{if idens > 0}this.{#UString(idensCol.Name)} = {#GetCsType(idensCol).Replace("?", "") == "long" ? "" : ("(" + GetCsType(idensCol) + ")")}freesql.Insert<{#UString(table.Name)}>().AppendData(this).ExecuteIdentity();{else}
			freesql.Insert<{#UString(table.Name)}>().AppendData(this).ExecuteAffrows();{/if}
		}
{/if}{/if}
	}
}