begin process at 2012 05 27 06:35:39
  Trouver un code source :
 
dans
 
Accueil > 

Code

 > 

Base de données

 > ENTITY FRAMEWORK - AVOIR UN INCLUDE TYPÉ

ENTITY FRAMEWORK - AVOIR UN INCLUDE TYPÉ


 Information sur la source

Note :
Aucune note
Catégorie :Base de données Source .NET ( DotNet ) Classé sous :Entity Framework, Include, EntityFramework, Linq Niveau :Débutant Date de création :17/01/2012 Date de mise à jour :17/01/2012 16:34:23 Vu :1 968

Auteur : jesusonline

Ecrire un message privé
Site perso
Ce membre participe au partage de revenus publicitaires
Commentaire sur cette source (0)
Ajouter un commentaire et/ou une note


 Description

Entity Framework propose une méhtode Include permettant d'inclure des objets connexes lors du chargement de certaines entités. Cette méthode prend un String en paramètre, ce qui ne permet pas d'avoir une vérification lors de la compilation.

Le bout de code ci-dessous permet de générer différentes méthodes Include permettant d'avoir des includes typés. Il existe de nombreuses solutions permettant d'attendre cette objectif, cette solution permet d'inclure plusieurs profondeurs d'objets connexes, y compris lorsqu'un de ces objets est une collection.

Il est ainsi possible de faire :

var q = entities.Orders.Include(o => o.Customer.Addresses, a => a.Country).Where(o => o.CustomerId == 3);

La source est composé de 2 fichiers, un fichier ExpressionExtensions contenant quelques méthodes d'extension permettant de connaitre le nom d'une propriété à partir d'une lambda et d'un fichier T4 générant les différentes méthodes Include.


Source

  • // ExpressionExtensions.cs
  • public static class ExpressionExtensions
  • {
  • public static String GetPropertyName<T, TProperty>(this Expression<Func<T, TProperty>> expression)
  • {
  • return GetPropertyName(expression);
  • }
  • public static String GetPropertyName(this Expression expression)
  • {
  • LambdaExpression lambdaExpression = expression as LambdaExpression;
  • if (lambdaExpression != null)
  • {
  • expression = lambdaExpression.Body;
  • }
  • MemberExpression memberExpression = expression as MemberExpression;
  • if (memberExpression != null)
  • {
  • String parentPropertyName = String.Empty;
  • if (memberExpression.Expression is MemberExpression)
  • {
  • parentPropertyName = ExpressionExtensions.GetPropertyName(memberExpression.Expression) + ".";
  • }
  • return parentPropertyName + memberExpression.Member.Name;
  • }
  • throw new NotImplementedException();
  • }
  • }
  • // ObjectQueryExtensions.Include.tt
  • <#@ template debug="true" hostSpecific="true" #>
  • <#@ output extension=".cs" #>
  • <#@ Assembly Name="System.Core.dll" #>
  • <#@ Assembly Name="System.Windows.Forms.dll" #>
  • <#@ import namespace="System" #>
  • <#@ import namespace="System.IO" #>
  • <#@ import namespace="System.Diagnostics" #>
  • <#@ import namespace="System.Linq" #>
  • <#@ import namespace="System.Collections" #>
  • <#@ import namespace="System.Collections.Generic" #>
  • <#
  • Byte maxDepth = 6;
  • #>
  • using System;
  • using System.Collections.Generic;
  • using System.Data.Objects;
  • using System.Data.Objects.DataClasses;
  • using System.Linq;
  • using System.Linq.Expressions;
  • namespace Magelia.WebStore.Data.Entities
  • {
  • public static partial class ObjectQueryExtensions
  • {
  • internal static String GetPath(params LambdaExpression[] lambdas)
  • {
  • return String.Join(".",
  • lambdas
  • .Select(l => l.GetPropertyName())
  • .ToArray()
  • );
  • }
  • <#
  • for(Byte i = 1; i < maxDepth; i++)
  • {
  • int combinationCount = (int)Math.Pow(2, i);
  • for (int j = 0; j < combinationCount; j++)
  • {
  • WriteMethod(i, j);
  • }
  • }
  • #>
  • }
  • }
  • <#+
  • void WriteMethod(Byte depth, int combinationValue)
  • {
  • String[] genericsType = new String[depth+1];
  • genericsType[0] = "TEntity";
  • int i = depth-1;
  • while (i >= 0)
  • {
  • String genericType = "T" + i.ToString();
  • if ((combinationValue & (1 << i)) != 0)
  • {
  • genericType = "IEnumerable<" + genericType + ">";
  • }
  • genericsType[i+1] = genericType;
  • i--;
  • }
  • String[] parametersType = new String[depth];
  • for(i = 0; i < depth; i++)
  • {
  • parametersType[i] = String.Format("Expression<Func<T{0}, {1}>> selector{2}", (i == 0) ? "Entity" : (i-1).ToString(), genericsType[i+1], i);
  • }
  • #>
  • public static ObjectQuery<TEntity> Include<TEntity, <#= String.Join(", ", Enumerable.Range(0, depth).Select(j => "T" + j.ToString()).ToArray()) #>>(this ObjectQuery<TEntity> objectSet, <#= String.Join(", ", parametersType) #>)
  • where TEntity : class
  • {
  • return objectSet.Include(GetPath(<#= String.Join(", ", Enumerable.Range(0, depth).Select(j => "selector" + j.ToString()).ToArray()) #>));
  • }
  • <#+
  • }
  • #>
// ExpressionExtensions.cs

    public static class ExpressionExtensions
    {
        public static String GetPropertyName<T, TProperty>(this Expression<Func<T, TProperty>> expression)
        {
            return GetPropertyName(expression);
        }
        public static String GetPropertyName(this Expression expression)
        {
            LambdaExpression lambdaExpression = expression as LambdaExpression;
            if (lambdaExpression != null)
            {
                expression = lambdaExpression.Body;
            }

            MemberExpression memberExpression = expression as MemberExpression;
            if (memberExpression != null)
            {
                String parentPropertyName = String.Empty;
                if (memberExpression.Expression is MemberExpression)
                {
                    parentPropertyName = ExpressionExtensions.GetPropertyName(memberExpression.Expression) + ".";
                }
                return parentPropertyName + memberExpression.Member.Name;
            }

            throw new NotImplementedException();
        }
    }

// ObjectQueryExtensions.Include.tt

<#@ template debug="true" hostSpecific="true" #>
<#@ output extension=".cs" #>
<#@ Assembly Name="System.Core.dll" #>
<#@ Assembly Name="System.Windows.Forms.dll" #>
<#@ import namespace="System" #>
<#@ import namespace="System.IO" #>
<#@ import namespace="System.Diagnostics" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Collections" #>
<#@ import namespace="System.Collections.Generic" #> 
<#
	Byte maxDepth = 6;
#>

using System;
using System.Collections.Generic;
using System.Data.Objects;
using System.Data.Objects.DataClasses;
using System.Linq;
using System.Linq.Expressions;

namespace Magelia.WebStore.Data.Entities
{
	public static partial class ObjectQueryExtensions
  	{
	    internal static String GetPath(params LambdaExpression[] lambdas)
        {
            return String.Join(".",
                lambdas
                .Select(l => l.GetPropertyName())
                .ToArray()
            );
        }

<#
	for(Byte i = 1; i < maxDepth; i++)
	{
        int combinationCount = (int)Math.Pow(2, i);
        for (int j = 0; j < combinationCount; j++)
        {
            WriteMethod(i, j); 
        }
	}
#>
  	}
}
 
<#+
  	void WriteMethod(Byte depth, int combinationValue)
	{
        String[] genericsType = new String[depth+1];
		genericsType[0] = "TEntity"; 
		int i = depth-1;
        while (i >= 0)
        {
			String genericType = "T" + i.ToString();
            if ((combinationValue & (1 << i)) != 0)
            {
                genericType = "IEnumerable<" + genericType + ">";
            }
			genericsType[i+1] = genericType; 
            i--;
        }
		String[] parametersType = new String[depth]; 
		for(i = 0; i < depth; i++)
		{
			parametersType[i] = String.Format("Expression<Func<T{0}, {1}>> selector{2}", (i == 0) ? "Entity" : (i-1).ToString(), genericsType[i+1], i); 
		}
#>
		public static ObjectQuery<TEntity> Include<TEntity, <#= String.Join(", ", Enumerable.Range(0, depth).Select(j => "T" + j.ToString()).ToArray()) #>>(this ObjectQuery<TEntity> objectSet, <#= String.Join(", ", parametersType) #>)
			where TEntity : class
		{
			return objectSet.Include(GetPath(<#= String.Join(", ", Enumerable.Range(0, depth).Select(j => "selector" + j.ToString()).ToArray()) #>));
		}
<#+
	}
#>


 Conclusion

Plus d'information sur mon blog : http://blogs.developpeur.org/cyril/archive/2012/01 /17/include-typ-et-entity-framework.aspx


 Historique

17 janvier 2012 16:34:26 :
ajout lien blog explicatif

 Sources du même auteur

Source .NET (Dotnet) WEBTESTPLUGIN - IGNORER DES URLS LORS D'UN TEST WEB VISUAL S...
Source avec Zip Source .NET (Dotnet) MECANISME DE SYNCHRONISATION DE THREAD - MONITOR, MUTEX, SEM...
Source avec Zip Source avec une capture Source .NET (Dotnet) GESTION DES IMPRIMANTES - ADDIN POUR WHS
Source .NET (Dotnet) CALCUL DES NOMBRES PREMIERS PAR LA CRIBLE D'ÉRATOSTHÈNE
Source .NET (Dotnet) MARQUER UN DOCUMENT OPENXML EN TANT QUE FINAL

 Sources de la même categorie

Source avec Zip APPLICATION BASE DE DONNÉES par pretude
Source avec Zip Source avec une capture Source .NET (Dotnet) CRÉATION DE CLASSES MÉTIERS À PARTIR D'UNE BASE DE DONNÉES par sebmafate
Source avec Zip Source avec une capture Source .NET (Dotnet) C# SQLCE DEMO par DanMor498
Source avec Zip EXPORTATION DE FICHIER CSV VERS UNE TABLE SQLSERVER par imothepe_33
Source .NET (Dotnet) CONNECTION SIMPLIFIER A LA BASE DE DONNÉE par audain

 Sources en rapport avec celle ci

Source avec Zip Source avec une capture Source .NET (Dotnet) [.NET3.5] SYSTEM.IO.PIPES - UTILISATION D'UN CANAL NOMMÉ par Willi
Source avec Zip Source avec une capture Source .NET (Dotnet) HOOK CLAVIER EN C# par shadow1779
Source avec Zip Source .NET (Dotnet) ARBRE (TREE) - STRUCTURES D'ARBRES GÉNÉRIQUES par ricklekebekoi
Source .NET (Dotnet) LINQ TO XML & LA MANIPULATION DE DONNÉES EN XML AVEC UNE APP... par driver
Source avec Zip Source avec une capture Source .NET (Dotnet) REDIMENSIONNEMENT DE DOCUMENTS SCANNÉS POUR MAILS par jmenfous

Commentaires et avis

Aucun commentaire pour le moment.

 Ajouter un commentaire


Discussions en rapport avec ce code source dans le forum

include ... [ par maevacmoi ] Hello !Je voudrais faire un site web (C#.net) avec des "include" comme en PHP, c'est à dire inclure une ou plusieures pages au sein d'une même page (s Feuille de style et "include" [ par Kati83 ] Bonjour à tous,Je voudrais vous poser 2 questions (pas très compliquées).La 1è : Si j'ai une page aspx qui contient beaucoup d'html, et pour le reste Obtenir les include des fichiers xsd (xsd:include) d'un schema [ par franckypoune ] Bonjour,J'ai un schema xsd qui contient des r&#233;f&#233;rences d'autres schemas xsd qui contiennent des types plus g&#233;n&#233;raux.Afin de r&#233 Question avec include [ par crahier ] Bonjour,Je suis confront&#233; &#224; petit probl&#232;me. c# 3.0 et linq [ par mathmax ] Bonjour,J'aimerais pouvoir utiliser c# 3.0 et linq. Pour celà, j'ai téléchargé et installé :.NET <span style="back [LINQ] - créer une requete dynamique (pas en dur) [ par romagny13 ] Bonjour,une question a propos de Linqvoilaj'ai essayé de me faire une pet WCF + Linq : Transmettre une arborescence d'objets [ par sebmafate ] Bonjour, J'utilise LinqToSql pour récupérer les informations de ma base de données et construire mes objets métiers. J'ai par exemple une class [LINQ] Problème de requête erreur : (nullreferencexception) [ par teddyalbina ] Salut !J'ai besoin de votre aide concernant une requete LINQ (c la première fois que j'utilise cette techno d'ailleur). Ma requete sert simplement a r [LINQ] besoin d'un coup de main avec linq et ooxml [ par teddyalbina ] Bonjour a tous j'ai besoin  de votre aide, pour une requête linq. Je veux récupérer dans un document OOXML les métadonnées ( titre, auteur etc...). Ma Question Linq très bête ... [ par oximoron ] J'utilise linq est j'ai un soucis très bête:J'ai une table Dossier avec 3 champs id et chemin et acceson va dire rempli avec un champ qui à un 'guid',


Nos sponsors


Sondage...

CalendriCode

Mai 2012
LMMJVSD
 123456
78910111213
14151617181920
21222324252627
28293031   

Consulter la suite du CalendriCode

Photothèque

A découvrir



 
Développement réalisé par Nicolas SOREL (Nix) avec l'aide de : Cyril DURAND et Emmanuel (EBArtSoft), Merci à Vincent pour ses précieux conseils.
CodeS-SourceS.com© Toute reproduction même partielle est interdite sauf accord écrit du Webmaster
CodeS-SourceS.com© est une marque déposée tous droits réservés

Google Coop CodeS-SourceS Google Coop CodeS-SourceS
Temps d'éxécution de la page : 1,014 sec (4)

Nous contacter | Annoncer sur CodeS-SourceS | Mentions légales