关于c#:从MetadataWorkspace读取MaxLength

发布时间 2023-07-19 13:46:03作者: hofmann
        string connectionString { get { return "Server=;Database=;Integrated Security=SSPI;"; } }

        [Test]
        public void Test()
        {
            using var dbcontext = new DB_Context(connectionString);
            var entity = new ResultInfoEntity();
            var maxLength = GetMaxLenth(dbcontext, nameof(ResultInfoEntity), nameof(entity.EntName));
        }

        private int GetMaxLenth(DbContext context, string entityName, string propertyName)
        {
            var tables = context.Model.GetEntityTypes();
            var table = tables.First(type => type.ClrType.Name == entityName);
            return table.FindProperty(propertyName).GetMaxLength() ?? -1;
        }