Come scoprire campo lunghezza massima in Entity Framework .NET a 4?
-
23-09-2019 - |
Domanda
questa domanda , non c'è modo integrato in EF v1 per capire la lunghezza di un campo. C'è una built-in modo per farlo in Entity Framework fornito con .NET 4, in caso affermativo - come?
Soluzione
Non c'è modo nuovo per accedere alla lunghezza di un immobile in EF 4.0. Hai ancora a camminare sopra i metadati -. Come mostrato nella risposta accettata sulla questione si fa riferimento
Altri suggerimenti
Questo agisce:
using System;
using System.Data.Objects;
using System.Data.Objects.DataClasses;
using System.Data.Metadata.Edm;
using System.Linq;
using System.Linq.Expressions;
namespace EfWidgets
{
public class EntityWidgets
{
public static int GetMaxLength<TEntity>(ObjectContext oc, Expression<Func<TEntity, string>> property)
where TEntity : EntityObject
{
var test = oc.MetadataWorkspace.GetItems(DataSpace.CSpace);
if (test == null)
return -1;
Type entType = typeof(TEntity);
string propertyName = ((MemberExpression)property.Body).Member.Name;
var q = test
.Where(m => m.BuiltInTypeKind == BuiltInTypeKind.EntityType)
.SelectMany(meta => ((EntityType)meta).Properties
.Where(p => p.Name == propertyName && p.TypeUsage.EdmType.Name == "String"));
var queryResult = q.Where(p =>
{
var match = p.DeclaringType.Name == entType.Name;
if (!match)
match = entType.Name == p.DeclaringType.Name;
return match;
})
.Select(sel => sel.TypeUsage.Facets["MaxLength"].Value)
.ToList();
if (queryResult.Any())
{
int result = Convert.ToInt32(queryResult.First());
return result;
}
return -1;
}
}
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow