Calendrier

Novembre 2009
L M M J V S D
            1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30            
<< < > >>

Présentation

Recherche

W3C

  • Flux RSS des articles

Linq To SQL

Linq to SQL Inheritance -  Guy Burstein 

Guy Burstein présente dans un premier temps les différentes stratégies pour modéliser un héritage (objet) avec une base de données puis comment Linq To SQL gère l'héritage (attributs,mapping,..)

How To: Model Inheritance in Databases 
Linq to SQL Inheritance


il présentait également comment définir le mapping :

 - par fichier xml avec Linq To SQL
 Linq To SQL Xml based mapping

 - par attributs
 Linq To SQL Attribute based mapping
Par Romagny13
Ecrire un commentaire - Voir les 0 commentaires - Recommander
Par Romagny13
Ecrire un commentaire - Voir les 0 commentaires - Recommander

[Tech Head Brothers] LINQ à 360 degré partie 4 consacrée à Linq disponible - LINQ to SQL

http://www.techheadbrothers.com/articles.aspx?id=99963165-48f8-4ea2-8ee1-cf36f376b8c7

Par Romagny13
Ecrire un commentaire - Voir les 0 commentaires - Recommander
[Linq To SQL ] – Astuce
Tracer les requêtes SQL exécutées
Très intéressant cela montre la requête SQL executée, et QUAND celle-ci l’est, dans mon exemple ce n’est qu’à la ligne > dataGridView1.DataSource = oContactCategories;
Que la requête est éxécutée
1 – avec la fenêtre Output (sortie)
Ajouter (db étant ici le DataContext)
db.Log = Console.Out;
 
Exemple
ContactDataContext db = new ContactDataContext();
           
            db.Log = Console.Out;
 
            System.Data.Linq.Table<ContactCategory> oContactCategories = db.GetTable<ContactCategory>();
 
            dataGridView1.DataSource = oContactCategories;
 
log1-copie-1.JPG
2 – Avec SQL Server Profiler
A condition bien entendu de disposer de SQL Server 2005 et non pas d’une version Express
log2.JPG
Par Romagny13
Ecrire un commentaire - Voir les 0 commentaires - Recommander
Utiliser les procédures stockées avec Linq To SQL

Depuis l’explorateur de serveurs, glisser les tables sur le Designer Linq To SQL 
stored1.JPG
Puis les procédures stockées désirées > celles-ci sont ajoutées dans le panneau « methods »
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [global::System.Data.Linq.StoredProcedure(Name="dbo.SelectContacts")]
        public global::System.Collections.Generic.IEnumerable<SelectContact> SelectContacts() {
            global::System.Data.Linq.Provider.IQueryResults<SelectContact> result = this.ExecuteMethodCall<SelectContact>(this, ((global::System.Reflection.MethodInfo)(global::System.Reflection.MethodInfo.GetCurrentMethod())));
            return ((global::System.Collections.Generic.IEnumerable<SelectContact>)(result));
        }
 
Le mécanisme de la reflection est utilisée pour appeler la procédure stockée définie en attribut
1 classe (portant le même nom que la procédure stockée)  pour les procédures SELECT est générée
stored2.JPG
Procédure Select
private void button1_Click(object sender, EventArgs e)
        {
            ContactsDataContext oContactsDataContext = new ContactsDataContext();
 
            System.Collections.Generic.IEnumerable<SelectContact> oContacts = oContactsDataContext.SelectContacts();
 
            dataGridView1.DataSource = oContacts.ToList();
        }
 
Procédure effectuant une mise à jour (Update)
Note : aucune classe n’a été générée en plus
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [global::System.Data.Linq.StoredProcedure(Name="dbo.UpdateContactCategory")]
        public int UpdateContactCategory([global::System.Data.Linq.Parameter(Name="@ContactCategoryID")] global::System.Nullable<int> ContactCategoryID, [global::System.Data.Linq.Parameter(Name="@ContactCategoryLib")] string ContactCategoryLib) {
            global::System.Data.Linq.Provider.IExecuteResults result = this.ExecuteMethodCall(this, ((global::System.Reflection.MethodInfo)(global::System.Reflection.MethodInfo.GetCurrentMethod())), ContactCategoryID, ContactCategoryLib);
            return ((int)(result.ReturnValue));
        }
 
 private void button2_Click(object sender, EventArgs e)
        {
            ContactsDataContext oContactsDataContext = new ContactsDataContext();
 
            int nResult = oContactsDataContext.UpdateContactCategory(1, "libellé modifié");
        }
 
stored3.JPG
Par Romagny13
Ecrire un commentaire - Voir les 0 commentaires - Recommander
 
[C# 3.0 Linq] Comparaison code saisi et code compilé
On constate que les requêtes Linq reposent sur les expressions Lambdas (qui sont une évolution des méthodes anonymes de .NET 2.0)
1 - Requête retournant une collection
 
var Query =
                from oContact in oContacts
                select oContact;
 
Reflector
 ParameterExpression CS$0$0000;
 
IQueryable<Contact> Query = 
this.oContacts.Select<Contact, Contact>(Expression.Lambda<Func<Contact, Contact>>
(CS$0$0000 = Expression.Parameter(typeof(Contact), "oContact"), 
new ParameterExpression[] { CS$0$0000 }));
 
 
Ainsi on peut trés bien remplacer dans le code de la form la requête Linq par afin d’obtenir le même résultat:
System.Linq.Expressions.ParameterExpression oParameterExpression;
 
IQueryable<Contact> Query = this.oContacts.Select<Contact, Contact>(System.Linq.Expressions.Expression.Lambda<Func<Contact, Contact>>(oParameterExpression = System.Linq.Expressions.Expression.Parameter(typeof(Contact), "oContact"), new System.Linq.Expressions.ParameterExpression[] { oParameterExpression }));
 
dataGridView1.DataSource = Query;
 
 
Avec Orderby
 var Query =
                from oContact in oContacts
                orderby oContact.ContactName
                select oContact;
 
Reflector
ParameterExpression CS$0$0000;
 
IOrderedQueryable<Contact> Query = this.oContacts.OrderBy<Contact, string>(Expression.Lambda<Func<Contact, string>>(Expression.Property(CS$0$0000 =
Expression.Parameter(typeof(Contact), "oContact"), (MethodInfo) methodof(Contact.get_ContactName)), new ParameterExpression[] { CS$0$0000 }));  
 
2 - Requête retournant un objet
 
var Query =
                (from oContact in oContacts
                 where oContact.ContactFirstName == "Dupond"
                 select oContact).First<Contact>();
            // automatiquement le type déduit est Contact donc on a accés aux propriétés de Contact
            Query.ContactName = "Martin";
 
 
Reflector
ParameterExpression CS$0$0000;
 
this.oContacts.Where<Contact>(Expression.Lambda<Func<Contact, bool>>
(Expression.Equal(Expression.Property(CS$0$0000 = Expression.Parameter(
typeof(Contact), "oContact"),(MethodInfo) methodof(Contact.get_ContactFirstName)), 
Expression.Constant("Dupond", typeof(string)), false, (MethodInfo) 
methodof(string.op_Equality)), new ParameterExpression[] 
{ CS$0$0000 })).First<Contact>().ContactName = "Martin";
 
 
 
Par Romagny13
Ecrire un commentaire - Voir les 0 commentaires - Recommander
Par Romagny13
Ecrire un commentaire - Voir les 0 commentaires - Recommander
Linq To SQL-Datacontext – initiation
 
Sommaire
I – définir soi-même ses classes pour accès aux données
II –avec un fichier LinqToSQL et le designer de Visual Studio Orcas
 
J’utilise un exemple très simple, une base de données ContactDB sur SQL Server 2005, et une seule table de la base : la table « Contact »
l3.JPG
I – définir soi – même ses classes pour accès aux données
1 – Ajouter une référence à System.Data.Linq.dll
2 – Ajouter les attributs [System.Data.Linq.Table()] and [System.Data.Linq.Column()]
-          Table > 
[System.Data.Linq.Table(Name = "dbo.Contact")]
 
-          Columns
o   Colonne correspondant à une clé primaire auto incrémentée >
[System.Data.Linq.Column(Storage="_ContactID", Name="ContactID", DBType="Int NOT NULL IDENTITY", IsPrimaryKey=true, IsDBGenerated=true, CanBeNull=false)]
 
o   Autres colonnes >
        [System.Data.Linq.Column(Storage = "_ContactName", Name = "ContactName", DBType = "Char(250)")]
 
3 – Faire hérité la classe de 
-          System.Data.Linq.INotifyPropertyChanging
-          System.ComponentModel.INotifyPropertyChanged
Implementer les 2 interfaces de classe > 2 événements sont générés
   #region INotifyPropertyChanged Members
 
        public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
 
        #endregion
 
        #region INotifyPropertyChanging Members
 
        public event System.ComponentModel.PropertyChangedEventHandler PropertyChanging;
 
        #endregion
 
4 – Ajouter 2 méthodes
protected void OnPropertyChanging(string propertyName)
        {
            if ((this.PropertyChanging != null))
            {
                this.PropertyChanging(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));
            }
        }
        protected void OnPropertyChanged(string propertyName)
        {
            if ((this.PropertyChanged != null))
            {
                this.PropertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));
            }
        }
 
5 – Modifier les properties de la classe (Set)
-          Pour les properties correspondant à une clé primaire auto incrémenté,laisser intact
[System.Data.Linq.Column(Storage="_ContactID", Name="ContactID", DBType="Int NOT NULL IDENTITY", IsPrimaryKey=true, IsDBGenerated=true, CanBeNull=false)]
        public Int32 ContactID
        {
            get { return _ContactID; }
            set { _ContactID = value; }
        }
 
 
-          Pour les properties correspondant à une colonne pouvant être null (AllowDBNull) – utiliser les Nullables
[System.Data.Linq.Column(Storage = "_ContactAge", Name = "ContactAge", DBType = "Int")]
        public Nullable<Int32> ContactAge
        {
            get { return _ContactAge; }
            set
            {
                if ((this._ContactAge != value))
                {
                    this.OnPropertyChanging("ContactAge");
                    this._ContactAge = value;
                    this.OnPropertyChanged("ContactAge");
                }
            }
        }
 
-          Pour les autres properties (ne correspondant donc ni à une clé primaire auto incrémentée, ni à une colonne acceptant les valeurs null)
 
[System.Data.Linq.Column(Storage = "_ContactName", Name = "ContactName", DBType = "Char(250)")]
        public String ContactName
        {
            get { return _ContactName; }
            set
            {
                if ((this._ContactName != value))
                {
                    this.OnPropertyChanging("ContactName");
                    this._ContactName = value;
                    this.OnPropertyChanged("ContactName");
                }
            }
        }
Par Romagny13
Ecrire un commentaire - Voir les 0 commentaires - Recommander
Finalement le code complet de la classe contact donne :
using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
 
namespace NET35CsDatacontext
{
    [System.Data.Linq.Table(Name = "dbo.Contact")]
    public class Contact : System.Data.Linq.INotifyPropertyChanging, System.ComponentModel.INotifyPropertyChanged
    {
        // Columns
        private Int32 _ContactID;
        private String _ContactName;
        private String _ContactFirstName;
        private String _ContactEmail;
        private Int32 _ContactTypeID;
        private Nullable<Int32> _ContactAge;
 
        // Constructors
        public Contact()
        { }
 
        // Properties
        [System.Data.Linq.Column(Storage="_ContactID", Name="ContactID", DBType="Int NOT NULL IDENTITY", IsPrimaryKey=true, IsDBGenerated=true, CanBeNull=false)]
        public Int32 ContactID
        {
            get { return _ContactID; }
            set { _ContactID = value; }
        }
        [System.Data.Linq.Column(Storage = "_ContactName", Name = "ContactName", DBType = "Char(250)")]
        public String ContactName
        {
            get { return _ContactName; }
            set
            {
                if ((this._ContactName != value))
                {
                    this.OnPropertyChanging("ContactName");
                    this._ContactName = value;
                    this.OnPropertyChanged("ContactName");
                }
            }
        }
        [System.Data.Linq.Column(Storage = "_ContactFirstName", Name = "ContactFirstName", DBType = "Char(250)")]
        public String ContactFirstName
        {
            get { return _ContactFirstName; }
            set
            {
                if ((this._ContactFirstName!= value))
                {
                    this.OnPropertyChanging("ContactFirstName");
                    this._ContactFirstName = value;
                    this.OnPropertyChanged("ContactFirstName");
                }
            }
        }
        [System.Data.Linq.Column(Storage = "_ContactEmail", Name = "ContactEmail", DBType = "Char(250)")]
        public String ContactEmail
        {
            get { return _ContactEmail; }
            set
            {
                if ((this._ContactEmail != value))
                {
                    this.OnPropertyChanging("ContactEmail");
                    this._ContactEmail = value;
                    this.OnPropertyChanged("ContactEmail");
                }
            }
        }
        [System.Data.Linq.Column(Storage = "_ContactTypeID", Name = "ContactTypeID", DBType = "Int")]
        public Int32 ContactTypeID
        {
            get { return _ContactTypeID; }
            set
            {
                if ((this._ContactTypeID != value))
                {
                    this.OnPropertyChanging("ContactTypeID");
                    this._ContactTypeID = value;
                    this.OnPropertyChanged("ContactTypeID");
                }
            }
        }
        [System.Data.Linq.Column(Storage = "_ContactAge", Name = "ContactAge", DBType = "Int")]
        public Nullable<Int32> ContactAge
        {
            get { return _ContactAge; }
            set
            {
                if ((this._ContactAge != value))
                {
                    this.OnPropertyChanging("ContactAge");
                    this._ContactAge = value;
                    this.OnPropertyChanged("ContactAge");
                }
            }
        }
 
        #region INotifyPropertyChanged Members
 
        public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
 
        #endregion
 
        #region INotifyPropertyChanging Members
 
        public event System.ComponentModel.PropertyChangedEventHandler PropertyChanging;
 
        #endregion
 
 
        protected void OnPropertyChanging(string propertyName)
        {
            if ((this.PropertyChanging != null))
            {
                this.PropertyChanging(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));
            }
        }
        protected void OnPropertyChanged(string propertyName)
        {
            if ((this.PropertyChanged != null))
            {
                this.PropertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));
            }
        }
    }
}
 
 
6 - Les 4 opérations de base – consultation,ajout,modification,suppression
Ne pas oublier oDataContext.SubmitChanges()pour valider les changements .
 
Code de la form
using System.Text;
using System.Windows.Forms;
 
namespace NET35CsDatacontext
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        // Declaration
        public System.Data.Linq.DataContext oDataContext;
        public System.Data.Linq.Table<Contact> oContacts;
 
        private void Form1_Load(object sender, EventArgs e)
        {
            // Initialisation
            oDataContext = new System.Data.Linq.DataContext(@"Data Source=.;Initial Catalog=ContactDB;Integrated Security=SSPI;");// chaine de connexion
            oContacts = oDataContext.GetTable<Contact>();
        }
 
        private void button1_Click(object sender, EventArgs e)
        {
            // 1 Read - consultation
            var Query =
                from oContact in oContacts
                orderby oContact.ContactName
                select oContact;
 
            // Affichage
            dataGridView1.DataSource = Query;
 
        }
 
        private void button2_Click(object sender, EventArgs e)
        {
            // 2 Add - Ajout
            Contact oContact = new Contact();
            oContact.ContactFirstName = "Martin";
            oContact.ContactName = "Louis";
 
            oContacts.Add(oContact);
            oDataContext.SubmitChanges();
        }
 
        private void button3_Click(object sender, EventArgs e)
        {
            // 3 Update - Modification
            var Query =
                (from oContact in oContacts
                 where oContact.ContactID == 7
                 select oContact).First<Contact>();
 
            // automatiquement le type déduit est Contact donc on a accés aux propriétés de Contact
            Query.ContactName = "Wang";
            oDataContext.SubmitChanges();
 
        }
 
        private void button4_Click(object sender, EventArgs e)
        {
            // 4 Remove - suppression
            var Query =
              (from oContact in oContacts
               where oContact.ContactID == 7
               select oContact).First();
 
            oContacts.Remove(Query);
            oDataContext.SubmitChanges();
        }
 
 
    }
}
 
l2.JPG
Par Romagny13
Ecrire un commentaire - Voir les 0 commentaires - Recommander
II – Avec un fichier Linq To SQL et le designer de Visual Studio Orcas
 
1 – Ajouter une référence à  System.Data.Linq.dll
2 – Explorateur de serveurs :
Ajouter une connexion à la base de données SQL Server 2005
Note : le designer des versions Express de Visual studio Orcas ne prennent en charge que les fichiers de bases de données SQL Server 2005 Express (pas sur server)
Les designers des versions de Visual Studio Orcas quand à elles prennent en charge égalment les bases de données sur serveur SQL Server 2005, actuellement Access (Jet) n’est pas pris en charge mais devrait l’être dans la version finale d’Orcas
 
3 - glisser les tables depuis l'explorateur de serveurs sur le designer de Orcas
l1.JPG
> Le code est automatiquement généré
>On peut modifier dans le designer (ajouter tables,supprimer colonnes,etc.), le code sera mis à jour
C’est l’utilitaire Sqlmetal.exe (que l’on peut donc utiliser en ligne de commande)
qui est utilisé pour généré le code depuis le designer de Orcas
il se trouve C:Program FilesMicrosoft Visual Studio 9.0SDKv3.5Bin (mais je ne suis pas sur que selon la version Express,beta,ctp,extension mai 2006 il ne soit pas dans un autre répertoire)
 
 
-          1 classe héritant de Datacontext est générée
-          1 classe par table glissée est générée (+ les relations), celles-ci héritent de
global::System.Data.Linq.INotifyPropertyChanging, global::System.ComponentModel.INotifyPropertyChanged
le code en fait est relativement simple, on retrouve tout ce qui a été défini dans la première partie du tutorial
 
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:2.0.50727.1302
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
 
namespace NET35CsDatacontextSqlMetal {
   
   
    public partial class ContactDataContext : global::System.Data.Linq.DataContext {
       
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        public ContactDataContext(string connection) :
                base(connection) {
        }
       
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        public ContactDataContext(global::System.Data.IDbConnection connection) :
                base(connection) {
        }
       
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        public ContactDataContext() :
                base(global::NET35CsDatacontextSqlMetal.Properties.Settings.Default.ContactDBConnectionString) {
        }
        
        public global::System.Data.Linq.Table<Contact> Contacts {
            get {
                return this.GetTable<Contact>();
            }
        }
    }
   
    [global::System.Data.Linq.Table(Name="dbo.Contact")]
    public partial class Contact : global::System.Data.Linq.INotifyPropertyChanging, global::System.ComponentModel.INotifyPropertyChanged {
       
        private int _ContactID;
       
        private string _ContactName;
       
        private string _ContactFirstName;
       
        private string _ContactEmail;
       
        private int _ContactTypeID;
       
        private global::System.Nullable<int> _ContactAge;
       
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        public Contact() {
            this._ContactID = default(int);
        }
       
        [global::System.Data.Linq.Column(Storage="_ContactID", Name="ContactID", DBType="Int NOT NULL IDENTITY", IsPrimaryKey=true, IsDBGenerated=true, CanBeNull=false)]
        public int ContactID {
            get {
                return this._ContactID;
            }
        }
       
        [global::System.Data.Linq.Column(Storage="_ContactName", Name="ContactName", DBType="Char(100) NOT NULL", CanBeNull=false)]
        public string ContactName {
            get {
                return this._ContactName;
            }
            set {
                if ((this._ContactName != value)) {
                    this.OnPropertyChanging("ContactName");
                    this._ContactName = value;
                    this.OnPropertyChanged("ContactName");
                }
            }
        }
       
        [global::System.Data.Linq.Column(Storage="_ContactFirstName", Name="ContactFirstName", DBType="Char(100) NOT NULL", CanBeNull=false)]
        public string ContactFirstName {
            get {
                return this._ContactFirstName;
            }
            set {
                if ((this._ContactFirstName != value)) {
                    this.OnPropertyChanging("ContactFirstName");
                    this._ContactFirstName = value;
                    this.OnPropertyChanged("ContactFirstName");
                }
            }
        }
       
        [global::System.Data.Linq.Column(Storage="_ContactEmail", Name="ContactEmail", DBType="Char(250)")]
        public string ContactEmail {
            get {
                return this._ContactEmail;
            }
            set {
                if ((this._ContactEmail != value)) {
                    this.OnPropertyChanging("ContactEmail");
                    this._ContactEmail = value;
                    this.OnPropertyChanged("ContactEmail");
                }
            }
        }
       
        [global::System.Data.Linq.Column(Storage="_ContactTypeID", Name="ContactTypeID", DBType="Int NOT NULL", CanBeNull=false)]
        public int ContactTypeID {
            get {
                return this._ContactTypeID;
            }
            set {
                if ((this._ContactTypeID != value)) {
                    this.OnPropertyChanging("ContactTypeID");
                    this._ContactTypeID = value;
                    this.OnPropertyChanged("ContactTypeID");
                }
            }
        }
       
        [global::System.Data.Linq.Column(Storage="_ContactAge", Name="ContactAge", DBType="Int")]
        public global::System.Nullable<int> ContactAge {
            get {
                return this._ContactAge;
            }
            set {
                if ((this._ContactAge != value)) {
                    this.OnPropertyChanging("ContactAge");
                    this._ContactAge = value;
                    this.OnPropertyChanged("ContactAge");
                }
            }
        }
       
        public event global::System.ComponentModel.PropertyChangedEventHandler PropertyChanging;
       
        public event global::System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
       
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        protected void OnPropertyChanging(string propertyName) {
            if ((this.PropertyChanging != null)) {
                this.PropertyChanging(this, new global::System.ComponentModel.PropertyChangedEventArgs(propertyName));
            }
        }
       
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        protected void OnPropertyChanged(string propertyName) {
            if ((this.PropertyChanged != null)) {
                this.PropertyChanged(this, new global::System.ComponentModel.PropertyChangedEventArgs(propertyName));
            }
        }
    }
}
 
 
4 – Utilisation – les 4 opérations de base (consultation, ajout, modification, suppression)
On fait appel au Datacontext généré (c’est la seule différence avec la première partie)
Code de la form
using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
 
namespace NET35CsDatacontextSqlMetal
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        public ContactDataContext oContactDataContext;
        public System.Data.Linq.Table<Contact> oContacts;
 
        private void Form1_Load(object sender, EventArgs e)
        {
            oContactDataContext = new ContactDataContext(); // ici inutile d'ajouter la chaine de connexion
            oContacts = oContactDataContext.GetTable<Contact>();
        }
 
        private void button1_Click(object sender, EventArgs e)
        {
            // 1 Read - consultation
            var Query =
                from oContact in oContacts
                orderby oContact.ContactName
                select oContact;
 
            // Affichage
            dataGridView1.DataSource = Query;
        }
 
        private void button2_Click(object sender, EventArgs e)
        {
            // 2 Add - Ajout
            Contact oContact = new Contact();
            oContact.ContactFirstName = "Petitsuisse";
            oContact.ContactName = "Henri";
 
            oContacts.Add(oContact);
            oContactDataContext.SubmitChanges();
        }
 
 
        private void button3_Click(object sender, EventArgs e)
        {
            // 3 Update - Modification
            var Query =
                (from oContact in oContacts
                 where oContact.ContactFirstName == "Petitsuisse"
                 select oContact).First<Contact>();
 
            // automatiquement le type déduit est Contact donc on a accés aux propriétés de Contact
            Query.ContactName = "GrandYoghourt";
            oContactDataContext.SubmitChanges();
 
        }
 
        private void button4_Click(object sender, EventArgs e)
        {
            // 4 Remove - suppression
            var Query =
              (from oContact in oContacts
               where oContact.ContactName == "GrandYoghourt"
               select oContact).First();
 
            oContacts.Remove(Query);
            oContactDataContext.SubmitChanges();
        }           
    }
}
 
Liens
101 queries
Linq project
 
Par Romagny13
Ecrire un commentaire - Voir les 0 commentaires - Recommander
[C# 3.0] - Les 4 opérations de bases avec DLinq
Consultation – Ajout – Modification – Suppression
 
>Ne pas oublier d’ajouter une référence à  System.Data.Linq.dll
>Ici j’utilise un Fichier LinqToSQL – sur lequel j’ai glissé les tables de ma base SQL Server 2005 depuis l’explorateur de serveurs grâce au designer de Visual Studio Orcas – le code est donc généré automatiquement
Important : si on n'utilise pas le designer et que l’on définie soi-même ses classes ne pas oublier de placer les attributs System.Data.Linq.Table et System.Data.Linq.Column , et surtout implémenter
System.Data.Linq.INotifyPropertyChanging,System.ComponentModel.INotifyPropertyChanged
 
Le code (j’accéde ici juste à une classique classe contact mon « hello world » pour les bases de données :p):
            ContactDataContext db;
            System.Data.Linq.Table<Contact> oContacts;
 
            db = new ContactDataContext();
            oContacts = db.GetTable<Contact>();
 
            // 1 Read - consultation
            var oSearchContacts = from oContact in oContacts
                                  orderby oContact.ContactName
                                  select oContact;
            // Affichage
            dataGridView1.DataSource = oSearchContacts;
 
 
 
 
 
 
 
 
 
            // 2 Add - Ajout
            Contact oContact = new Contact();
            oContact.ContactFirstName = "BonBlanc";
            oContact.ContactName = "Jean";
           
           oContacts.Add(oContact);
            db.SubmitChanges();
 
 
 
 
 
 
 
 
 
 
 
 
            // 3 Update - Modification
            var Query =
                (from oContact in oContacts
                 where oContact.ContactID == 22
                 select oContact).First<Contact>();
 
            // automatiquement le type déduit est Contact donc on a accés aux propriétés de Contact
            Query.ContactName = "Autre nom";
            db.SubmitChanges();
 
 
 
 
 
 
 
            // 4 Remove - suppression
            var Query =
              (from oContact in oContacts
               where oContact.ContactID == 21
               select oContact).First();
 
            oContacts.Remove(Query);
            db.SubmitChanges();
 
Par Romagny13
Ecrire un commentaire - Voir les 0 commentaires - Recommander
Linq To SQL - Initiation
 
Ici j’utilise la version Express de Visual Studio Orcas Beta 1 (celle-ci ne prend en charge que les fichiers de base de données SQL Server 2005 Express,j’espère que dans la version finale les bases SQL Server seront au moins reconnues voir Access également)
 (Créer un nouveau projet Windows Forms)
1 – Ajouter un nouvel élément > Linq To SQL File
OR1.JPG
2 – on se retrouve dans le designer de Visual Studio Orcas
OR3.JPG
>après avoir ajouter une connexion depuis l’explorateur de serveurs à la base (*.mdf) SQL Server 2005
>glisser sur le designer les tables depuis l’explorateur de serveurs
 
Le code est généré automatiquement (grâce à l’utilitaire SqlMetal du framework 3.5)
Note : on peut supprimer des colonnes dans le designer, le code généré sera automatiquement mis à jour
Si on regarde côté designer.cs du fichier Linq To SQL
On remarque :
-          La classe DataContext (dans mon exemple ContactsDataContext) hérite de System.Data.Linq.DataContext
-          Chaque classe correspondante à la table glissée depuis l’explorateur a un attribut Table   ex :[global::System.Data.Linq.Table(Name="dbo.CONTACT")]
-          Chaque property a un attribut Column ex :
        [global::System.Data.Linq.Column(Storage="_ContactID", Name="ContactID", DBType="Int NOT NULL IDENTITY", IsPrimaryKey=true, IsDBGenerated=true, CanBeNull=false)]
Code complet de la classe Contacts.Designer.cs
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:2.0.50727.1318
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
 
namespace TestLinqToSql {
   
   
    public partial class ContactsDataContext : global::System.Data.Linq.DataContext {
       
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        public ContactsDataContext(string connection) :
                base(connection) {
        }
       
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        public ContactsDataContext(global::System.Data.IDbConnection connection) :
                base(connection) {
        }
       
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        public ContactsDataContext() :
                base(global::TestLinqToSql.Properties.Settings.Default.ContactDBConnectionString) {
        }
       
        public global::System.Data.Linq.Table<CONTACT> CONTACTs {
            get {
                return this.GetTable<CONTACT>();
            }
        }
    }
   
    [global::System.Data.Linq.Table(Name="dbo.CONTACT")]
    public partial class CONTACT : global::System.Data.Linq.INotifyPropertyChanging, global::System.ComponentModel.INotifyPropertyChanged {
       
        private int _ContactID;
       
        private string _ContactName;
       
        private string _ContactFirstName;
       
        private string _ContactType;
       
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        public CONTACT() {
            this._ContactID = default(int);
        }
       
        [global::System.Data.Linq.Column(Storage="_ContactID", Name="ContactID", DBType="Int NOT NULL IDENTITY", IsPrimaryKey=true, IsDBGenerated=true, CanBeNull=false)]
        public int ContactID {
            get {
                return this._ContactID;
            }
        }
       
        [global::System.Data.Linq.Column(Storage="_ContactName", Name="ContactName", DBType="Char(50)")]
        public string ContactName {
            get {
                return this._ContactName;
            }
            set {
                if ((this._ContactName != value)) {
                    this.OnPropertyChanging("ContactName");
                    this._ContactName = value;
                    this.OnPropertyChanged("ContactName");
                }
            }
        }
       
        [global::System.Data.Linq.Column(Storage="_ContactFirstName", Name="ContactFirstName", DBType="Char(50)")]
        public string ContactFirstName {
            get {
                return this._ContactFirstName;
            }
            set {
                if ((this._ContactFirstName != value)) {
                    this.OnPropertyChanging("ContactFirstName");
                    this._ContactFirstName = value;
                    this.OnPropertyChanged("ContactFirstName");
                }
            }
        }
       
        [global::System.Data.Linq.Column(Storage="_ContactType", Name="ContactType", DBType="Char(50)")]
        public string ContactType {
            get {
                return this._ContactType;
            }
            set {
                if ((this._ContactType != value)) {
                    this.OnPropertyChanging("ContactType");
                    this._ContactType = value;
                    this.OnPropertyChanged("ContactType");
                }
            }
        }
       
        public event global::System.ComponentModel.PropertyChangedEventHandler PropertyChanging;
       
        public event global::System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
       
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        protected void OnPropertyChanging(string propertyName) {
            if ((this.PropertyChanging != null)) {
                this.PropertyChanging(this, new global::System.ComponentModel.PropertyChangedEventArgs(propertyName));
            }
        }
       
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        protected void OnPropertyChanged(string propertyName) {
            if ((this.PropertyChanged != null)) {
                this.PropertyChanged(this, new global::System.ComponentModel.PropertyChangedEventArgs(propertyName));
            }
        }
    }
}
 
 
 
Finalement l’accès aux données de sa base est très simplifié
Dans le code de la form
// DataContext
            ContactsDataContext oContactsDataContext = new ContactsDataContext();
            // la connexion est définie dans les settings du projet mais on peut la préciser si besoin
            //ContactsDataContext oContactsDataContext = new ContactsDataContext(@"Data Source=.SQLEXPRESS;AttachDbFilename=C:ContactDB.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
 
            //
            System.Data.Linq.Table<CONTACT> oContacts = oContactsDataContext.GetTable<CONTACT>();
 
            // une "requête" Linq
            var oSearchContacts = from oContact in oContacts
                                  orderby oContact.ContactName
                                  select oContact;
            // Affichage
            dataGridView1.DataSource = oSearchContacts;
 
 
> on peut également ne pas passer par le designer et les fichiers Linq To SQL
 
public void TestDLinq()
        {
            // Connexion à une base de données Sql Server
            System.Data.Linq.DataContext oDataContext;;
            oDataContext = new System.Data.Linq.DataContext(@"Data Source=DONJR;Initial Catalog=ContactDB;Integrated Security=SSPI;");
 
            System.Data.Linq.Table<Contact> oContacts = oDataContext.GetTable<Contact>();
 
 
            // execution d'une requête simple
            var oSearchContacts = from oContact in oContacts
                                  where oContact.ContactName.StartsWith("B")
                                  select oContact;
 
            // Affichage
            foreach (Contact oContact in oSearchContacts)
            {
                listBox1.Items.Add(oContact.ContactName + " " + oContact.ContactFirstName);
            }
          
        }
 
Par Romagny13
Ecrire un commentaire - Voir les 0 commentaires - Recommander
Créer un blog sur over-blog.com - Contact - C.G.U. - Rémunération en droits d'auteur - Signaler un abus