MSSQL 的方法
public int GetColumnMaxLength(string tableName, string columnName)
{
int result = -1;
using(var conn = new SqlConnection("ConnectionString"))
{
conn.Open();
var cmd = new SqlCommand("SELECT * FROM "+tableName+" WHERE 1 = 0", conn);
var reader = cmd.ExecuteReader();
var schema = reader.GetSchemaTable();
result = schema.AsEnumerable()
.Single(s => s.Field<string>("ColumnName") == "Column")
.Field<int>("ColumnSize");
conn.Close();
}
return result;
}
加個database上去比較好
public int GetColumnMaxLength(string dbname ,string tableName, string columnName)
{
int result = -1;
using(var conn = new SqlConnection("ConnectionString"))
{
conn.Open();
var cmd = new SqlCommand("SELECT * FROM "+dbname+".dbo."tableName+" WHERE 1 = 0", conn);
var reader = cmd.ExecuteReader();
var schema = reader.GetSchemaTable();
result = schema.AsEnumerable()
.Single(s => s.Field<string>("ColumnName") == "Column")
.Field<int>("ColumnSize");
conn.Close();
}
return result;
}
你是EF Core的話,你可以在Entity設定欄位狀態
或是自己寫簡單的驗證
public class Program
{
static async Task Main(string[] args)
{
List<Student> student = new List<Student>
{
new Student { Name = "一" },
new Student { Name = "一二" },
new Student { Name = "一二三" },
new Student { Name = "一二三四" },
new Student { Name = "一二三四五" }
};
Console.WriteLine(string.Join(",", student.Select(x=>x.Name)));
Console.ReadKey();
}
public class Student
{
private string _name;
public string Name
{
get
{
if (_name.Length <= 3)
return _name;
return "溢位";
}
set { _name = value; }
}
}
}