Bienvenue à Blogs CodeS-SourceS Identification | Inscription | Aide

Abonnements

POCO, les joies du T4, la suite

Hier, j’ai bloggé sur mon pattern de génération T4. En discutant un petit peu, j’ai pu me rendre compte qu’un complément d’information n'était pas superflu.

Je me suis généré le modèle d’entité suivant :

image

Première nouveauté avec VS 2010 Beta, les complex properties dans le designer (ici Address) sont supportés, même si le fait de ne pas avoir le complex type dans le designer (en dehors de la fenêtre Model Browser) est à mon avis dommage. // Si on rajoute à cela le non support des mappings TPC et de l’Horizontal Entity Splitting, je pense que mon EDM Designer devrait continuer d’être intéressant (en attendant VS 2012). Matthieu 1 - ADO .NET Team 0 Stick out tongue

Bref, EF is good quand même Big Smile

Pour réaliser mon exemple, je suis parti sur une approche Model First. C’est à dire que j’ai d’abord créer mon modèle d’entités et que je lui ai ensuite demandé de me générer la base qui va bien à partir de celles-ci. C’est est également une nouveauté de la V2. // A noter que je préfère l’approche dans laquelle le DBA conçoit la base et l’architecte conçoit les entités, le tout indépendamment. Ensuite, il suffit d’utiliser la puissance du mapping d’EDM pour mapper les deux conceptions (objet et relationnel).

Bref, revenons à nos moutons ou plutôt à nos entités. Smile

Comme l’explique Alex dans son post, il est possible d’utiliser le template T4 pour générer le code des entités.

Mon idée était de faire un template POCO. L’ADO .NET team devrait également en publier prochainement comme l’écrit Alex (après moi Stick out tongue). Matthieu 2 - ADO .NET Team 0 Stick out tongue

Avec le code généré par défaut (avec ou sans le template T4), les entités générées sont des entités Prescriptive classes (ie : devant hériter des classes de base du Framework).

Dans l’exemple, voici le code généré :

using System;

using System.Data.Objects;

using System.Data.Objects.DataClasses;

using System.Data.EntityClient;

using System.ComponentModel;

using System.Xml.Serialization;

using System.Runtime.Serialization;

 

[assembly: EdmSchemaAttribute()]

 

#region EDM Relationship Metadata

[assembly: EdmRelationshipAttribute("Test", "CategoryProduct", "Category", System.Data.Metadata.Edm.RelationshipMultiplicity.ZeroOrOne, typeof(ConsoleApplication1.Category), "Product", System.Data.Metadata.Edm.RelationshipMultiplicity.Many, typeof(ConsoleApplication1.Product))]

[assembly: EdmRelationshipAttribute("Test", "SupplierProduct", "Supplier", System.Data.Metadata.Edm.RelationshipMultiplicity.ZeroOrOne, typeof(ConsoleApplication1.Supplier), "Product", System.Data.Metadata.Edm.RelationshipMultiplicity.Many, typeof(ConsoleApplication1.Product))]

#endregion

 

namespace ConsoleApplication1

{

    #region Contexts

    /// <summary>

    /// No Metadata Documentation available.

    /// </summary>

    public partial class TestContainer : ObjectContext

    {

        #region Constructors

        /// <summary>

        /// Initializes a new TestContainer object using the connection string found in the 'TestContainer' section of the application configuration file.

        /// </summary>

        public TestContainer()

            : base("name=TestContainer", "TestContainer")

        {

            OnContextCreated();

        }

 

        /// <summary>

        /// Initialize a new TestContainer object.

        /// </summary>

        public TestContainer(string connectionString)

            : base(connectionString, "TestContainer")

        {

            OnContextCreated();

        }

 

        /// <summary>

        /// Initialize a new TestContainer object.

        /// </summary>

        public TestContainer(EntityConnection connection)

            : base(connection, "TestContainer")

        {

            OnContextCreated();

        }

        #endregion

 

        #region Partial Methods

        partial void OnContextCreated();

        #endregion

 

        #region ObjectSet Properties

        /// <summary>

        /// No Metadata Documentation available.

        /// </summary>

        public ObjectSet<Category> Categories

        {

            get

            {

                if ((_Categories == null))

                {

                    _Categories = base.CreateObjectSet<Category>("Categories");

                }

                return _Categories;

            }

        }

        private ObjectSet<Category> _Categories;

 

        /// <summary>

        /// No Metadata Documentation available.

        /// </summary>

        public ObjectSet<Product> Products

        {

            get

            {

                if ((_Products == null))

                {

                    _Products = base.CreateObjectSet<Product>("Products");

                }

                return _Products;

            }

        }

        private ObjectSet<Product> _Products;

 

        /// <summary>

        /// No Metadata Documentation available.

        /// </summary>

        public ObjectSet<Supplier> Suppliers

        {

            get

            {

                if ((_Suppliers == null))

                {

                    _Suppliers = base.CreateObjectSet<Supplier>("Suppliers");

                }

                return _Suppliers;

            }

        }

        private ObjectSet<Supplier> _Suppliers;

 

        #endregion

        #region AddTo Methods

 

        /// <summary>

        /// Deprecated Method for adding a new object to the Categories EntitySet. Consider using the .Add method of the associated ObjectSet&lt;T&gt; property instead.

        /// </summary>

        public void AddToCategories(Category category)

        {

            base.AddObject("Categories", category);

        }

 

        /// <summary>

        /// Deprecated Method for adding a new object to the Products EntitySet. Consider using the .Add method of the associated ObjectSet&lt;T&gt; property instead.

        /// </summary>

        public void AddToProducts(Product product)

        {

            base.AddObject("Products", product);

        }

 

        /// <summary>

        /// Deprecated Method for adding a new object to the Suppliers EntitySet. Consider using the .Add method of the associated ObjectSet&lt;T&gt; property instead.

        /// </summary>

        public void AddToSuppliers(Supplier supplier)

        {

            base.AddObject("Suppliers", supplier);

        }

        #endregion

    }

 

    #endregion

 

 

    #region Entities

    /// <summary>

    /// No Metadata Documentation available.

    /// </summary>

    [EdmEntityTypeAttribute(NamespaceName = "Test", Name = "Category")]

    [Serializable()]

    [DataContractAttribute(IsReference = true)]

    public partial class Category : EntityObject

    {

        #region Factory Method

        /// <summary>

        /// Create a new Category object.

        /// </summary>

        /// <param name="id">Initial value of the Id property.</param>

        /// <param name="name">Initial value of the Name property.</param>

        /// <param name="description">Initial value of the Description property.</param>

        public static Category CreateCategory(global::System.Int32 id, global::System.String name, global::System.String description)

        {

            Category category = new Category();

            category.Id = id;

 

            category.Name = name;

 

            category.Description = description;

 

            return category;

        }

        #endregion

 

        #region Primitive Properties

        /// <summary>

        /// No Metadata Documentation available.

        /// </summary>

        [EdmScalarPropertyAttribute(EntityKeyProperty = true, IsNullable = false)]

        [DataMemberAttribute()]

        public global::System.Int32 Id

        {

            get

            {

                return _Id;

            }

            set

            {

                if (Id != value)

                {

                    OnIdChanging(value);

                    ReportPropertyChanging("Id");

                    _Id = StructuralObject.SetValidValue(value);

                    ReportPropertyChanged("Id");

                    OnIdChanged();

                }

            }

 

        }

        private global::System.Int32 _Id;

        partial void OnIdChanging(global::System.Int32 value);

        partial void OnIdChanged();

 

        /// <summary>

        /// No Metadata Documentation available.

        /// </summary>

        [EdmScalarPropertyAttribute(EntityKeyProperty = false, IsNullable = false)]

        [DataMemberAttribute()]

        public global::System.String Name

        {

            get

            {

                return _Name;

            }

            set

            {

                OnNameChanging(value);

                ReportPropertyChanging("Name");

                _Name = StructuralObject.SetValidValue(value, false);

                ReportPropertyChanged("Name");

                OnNameChanged();

            }

 

        }

        private global::System.String _Name;

        partial void OnNameChanging(global::System.String value);

        partial void OnNameChanged();

 

        /// <summary>

        /// No Metadata Documentation available.

        /// </summary>

        [EdmScalarPropertyAttribute(EntityKeyProperty = false, IsNullable = false)]

        [DataMemberAttribute()]

        public global::System.String Description

        {

            get

            {

                return _Description;

            }

            set

            {

                OnDescriptionChanging(value);

                ReportPropertyChanging("Description");

                _Description = StructuralObject.SetValidValue(value, false);

                ReportPropertyChanged("Description");

                OnDescriptionChanged();

            }

 

        }

        private global::System.String _Description;

        partial void OnDescriptionChanging(global::System.String value);

        partial void OnDescriptionChanged();

 

        #endregion

 

        #region Navigation Properties

        /// <summary>

        /// No Metadata Documentation available.

        /// </summary>

        [XmlIgnoreAttribute()]

        [SoapIgnoreAttribute()]

        [DataMemberAttribute()]

        [EdmRelationshipNavigationPropertyAttribute("Test", "CategoryProduct", "Product")]

        public EntityCollection<Product> Products

        {

            get

            {

                return ((IEntityWithRelationships)this).RelationshipManager.GetRelatedCollection<Product>("Test.CategoryProduct", "Product");

            }

            set

            {

                if ((value != null))

                {

                    ((IEntityWithRelationships)this).RelationshipManager.InitializeRelatedCollection<Product>("Test.CategoryProduct", "Product", value);

                }

            }

        }

        #endregion

    }

 

    /// <summary>

    /// No Metadata Documentation available.

    /// </summary>

    [EdmEntityTypeAttribute(NamespaceName = "Test", Name = "Product")]

    [Serializable()]

    [DataContractAttribute(IsReference = true)]

    public partial class Product : EntityObject

    {

        #region Factory Method

        /// <summary>

        /// Create a new Product object.

        /// </summary>

        /// <param name="id">Initial value of the Id property.</param>

        /// <param name="name">Initial value of the Name property.</param>

        public static Product CreateProduct(global::System.Int32 id, global::System.String name)

        {

            Product product = new Product();

            product.Id = id;

 

            product.Name = name;

 

            return product;

        }

        #endregion

 

        #region Primitive Properties

        /// <summary>

        /// No Metadata Documentation available.

        /// </summary>

        [EdmScalarPropertyAttribute(EntityKeyProperty = true, IsNullable = false)]

        [DataMemberAttribute()]

        public global::System.Int32 Id

        {

            get

            {

                return _Id;

            }

            set

            {

                if (Id != value)

                {

                    OnIdChanging(value);

                    ReportPropertyChanging("Id");

                    _Id = StructuralObject.SetValidValue(value);

                    ReportPropertyChanged("Id");

                    OnIdChanged();

                }

            }

 

        }

        private global::System.Int32 _Id;

        partial void OnIdChanging(global::System.Int32 value);

        partial void OnIdChanged();

 

        /// <summary>

        /// No Metadata Documentation available.

        /// </summary>

        [EdmScalarPropertyAttribute(EntityKeyProperty = false, IsNullable = false)]

        [DataMemberAttribute()]

        public global::System.String Name

        {

            get

            {

                return _Name;

            }

            set

            {

                OnNameChanging(value);

                ReportPropertyChanging("Name");

                _Name = StructuralObject.SetValidValue(value, false);

                ReportPropertyChanged("Name");

                OnNameChanged();

            }

 

        }

        private global::System.String _Name;

        partial void OnNameChanging(global::System.String value);

        partial void OnNameChanged();

 

        #endregion

 

        #region Navigation Properties

        /// <summary>

        /// No Metadata Documentation available.

        /// </summary>

        [XmlIgnoreAttribute()]

        [SoapIgnoreAttribute()]

        [DataMemberAttribute()]

        [EdmRelationshipNavigationPropertyAttribute("Test", "CategoryProduct", "Category")]

        public Category Category

        {

            get

            {

                return ((IEntityWithRelationships)this).RelationshipManager.GetRelatedReference<Category>("Test.CategoryProduct", "Category").Value;

            }

            set

            {

                ((IEntityWithRelationships)this).RelationshipManager.GetRelatedReference<Category>("Test.CategoryProduct", "Category").Value = value;

            }

        }

        /// <summary>

        /// No Metadata Documentation available.

        /// </summary>

        [BrowsableAttribute(false)]

        [DataMemberAttribute()]

        public EntityReference<Category> CategoryReference

        {

            get

            {

                return ((IEntityWithRelationships)this).RelationshipManager.GetRelatedReference<Category>("Test.CategoryProduct", "Category");

            }

            set

            {

                if ((value != null))

                {

                    ((IEntityWithRelationships)this).RelationshipManager.InitializeRelatedReference<Category>("Test.CategoryProduct", "Category", value);

                }

            }

        }

        /// <summary>

        /// No Metadata Documentation available.

        /// </summary>

        [XmlIgnoreAttribute()]

        [SoapIgnoreAttribute()]

        [DataMemberAttribute()]

        [EdmRelationshipNavigationPropertyAttribute("Test", "SupplierProduct", "Supplier")]

        public Supplier Supplier

        {

            get

            {

                return ((IEntityWithRelationships)this).RelationshipManager.GetRelatedReference<Supplier>("Test.SupplierProduct", "Supplier").Value;

            }

            set

            {

                ((IEntityWithRelationships)this).RelationshipManager.GetRelatedReference<Supplier>("Test.SupplierProduct", "Supplier").Value = value;

            }

        }

        /// <summary>

        /// No Metadata Documentation available.

        /// </summary>

        [BrowsableAttribute(false)]

        [DataMemberAttribute()]

        public EntityReference<Supplier> SupplierReference

        {

            get

            {

                return ((IEntityWithRelationships)this).RelationshipManager.GetRelatedReference<Supplier>("Test.SupplierProduct", "Supplier");

            }

            set

            {

                if ((value != null))

                {

                    ((IEntityWithRelationships)this).RelationshipManager.InitializeRelatedReference<Supplier>("Test.SupplierProduct", "Supplier", value);

                }

            }

        }

        #endregion

    }

 

    /// <summary>

    /// No Metadata Documentation available.

    /// </summary>

    [EdmEntityTypeAttribute(NamespaceName = "Test", Name = "Supplier")]

    [Serializable()]

    [DataContractAttribute(IsReference = true)]

    public partial class Supplier : EntityObject

    {

        #region Factory Method

        /// <summary>

        /// Create a new Supplier object.

        /// </summary>

        /// <param name="id">Initial value of the Id property.</param>

        /// <param name="companyName">Initial value of the CompanyName property.</param>

        /// <param name="address">Initial value of the Address property.</param>

        public static Supplier CreateSupplier(global::System.Int32 id, global::System.String companyName, Address address)

        {

            Supplier supplier = new Supplier();

            supplier.Id = id;

 

            supplier.CompanyName = companyName;

 

            supplier.Address = StructuralObject.VerifyComplexObjectIsNotNull(address, "Address");

            return supplier;

        }

        #endregion

 

        #region Primitive Properties

        /// <summary>

        /// No Metadata Documentation available.

        /// </summary>

        [EdmScalarPropertyAttribute(EntityKeyProperty = true, IsNullable = false)]

        [DataMemberAttribute()]

        public global::System.Int32 Id

        {

            get

            {

                return _Id;

            }

            set

            {

                if (Id != value)

                {

                    OnIdChanging(value);

                    ReportPropertyChanging("Id");

                    _Id = StructuralObject.SetValidValue(value);

                    ReportPropertyChanged("Id");

                    OnIdChanged();

                }

            }

 

        }

        private global::System.Int32 _Id;

        partial void OnIdChanging(global::System.Int32 value);

        partial void OnIdChanged();

 

        /// <summary>

        /// No Metadata Documentation available.

        /// </summary>

        [EdmScalarPropertyAttribute(EntityKeyProperty = false, IsNullable = false)]

        [DataMemberAttribute()]

        public global::System.String CompanyName

        {

            get

            {

                return _CompanyName;

            }

            set

            {

                OnCompanyNameChanging(value);

                ReportPropertyChanging("CompanyName");

                _CompanyName = StructuralObject.SetValidValue(value, false);

                ReportPropertyChanged("CompanyName");

                OnCompanyNameChanged();

            }

 

        }

        private global::System.String _CompanyName;

        partial void OnCompanyNameChanging(global::System.String value);

        partial void OnCompanyNameChanged();

 

        #endregion

        #region Complex Properties

 

        /// <summary>

        /// No Metadata Documentation available.

        /// </summary>

        [EdmComplexPropertyAttribute()]

        [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]

        [XmlElement(IsNullable = true)]

        [SoapElement(IsNullable = true)]

        [DataMemberAttribute()]

        public Address Address

        {

            get

            {

                _Address = GetValidValue(_Address, "Address", false, _AddressInitialized);

                _AddressInitialized = true;

                return _Address;

            }

            set

            {

                OnAddressChanging(value);

                ReportPropertyChanging("Address");

                _Address = SetValidValue(_Address, value, "Address");

                _AddressInitialized = true;

                ReportPropertyChanged("Address");

                OnAddressChanged();

            }

        }

        private Address _Address;

        private bool _AddressInitialized;

        partial void OnAddressChanging(Address value);

        partial void OnAddressChanged();

        #endregion

 

        #region Navigation Properties

        /// <summary>

        /// No Metadata Documentation available.

        /// </summary>

        [XmlIgnoreAttribute()]

        [SoapIgnoreAttribute()]

        [DataMemberAttribute()]

        [EdmRelationshipNavigationPropertyAttribute("Test", "SupplierProduct", "Product")]

        public EntityCollection<Product> Products

        {

            get

            {

                return ((IEntityWithRelationships)this).RelationshipManager.GetRelatedCollection<Product>("Test.SupplierProduct", "Product");

            }

            set

            {

                if ((value != null))

                {

                    ((IEntityWithRelationships)this).RelationshipManager.InitializeRelatedCollection<Product>("Test.SupplierProduct", "Product", value);

                }

            }

        }

        #endregion

    }

 

    #endregion

    #region ComplexTypes

    /// <summary>

    /// No Metadata Documentation available.

    /// </summary>

    [EdmComplexTypeAttribute(NamespaceName = "Test", Name = "Address")]

    [DataContractAttribute(IsReference = true)]

    [Serializable()]

    public partial class Address : ComplexObject

    {

        #region Factory Method

        /// <summary>

        /// Create a new Address object.

        /// </summary>

        /// <param name="addressLine">Initial value of the AddressLine property.</param>

        /// <param name="postalCode">Initial value of the PostalCode property.</param>

        /// <param name="city">Initial value of the City property.</param>

        /// <param name="region">Initial value of the Region property.</param>

        /// <param name="country">Initial value of the Country property.</param>

        public static Address CreateAddress(global::System.String addressLine, global::System.String postalCode, global::System.String city, global::System.String region, global::System.String country)

        {

            Address address = new Address();

            address.AddressLine = addressLine;

 

            address.PostalCode = postalCode;

 

            address.City = city;

 

            address.Region = region;

 

            address.Country = country;

 

            return address;

        }

        #endregion

 

        #region Primitive Properties

        /// <summary>

        /// No Metadata Documentation available.

        /// </summary>

        [EdmScalarPropertyAttribute(EntityKeyProperty = false, IsNullable = false)]

        [DataMemberAttribute()]

        public global::System.String AddressLine

        {

            get

            {

                return _AddressLine;

            }

            set

            {

                OnAddressLineChanging(value);

                ReportPropertyChanging("AddressLine");

                _AddressLine = StructuralObject.SetValidValue(value, false);

                ReportPropertyChanged("AddressLine");

                OnAddressLineChanged();

            }

 

        }

        private global::System.String _AddressLine;

        partial void OnAddressLineChanging(global::System.String value);

        partial void OnAddressLineChanged();

 

        /// <summary>

        /// No Metadata Documentation available.

        /// </summary>

        [EdmScalarPropertyAttribute(EntityKeyProperty = false, IsNullable = false)]

        [DataMemberAttribute()]

        public global::System.String PostalCode

        {

            get

            {

                return _PostalCode;

            }

            set

            {

                OnPostalCodeChanging(value);

                ReportPropertyChanging("PostalCode");

                _PostalCode = StructuralObject.SetValidValue(value, false);

                ReportPropertyChanged("PostalCode");

                OnPostalCodeChanged();

            }

 

        }

        private global::System.String _PostalCode;

        partial void OnPostalCodeChanging(global::System.String value);

        partial void OnPostalCodeChanged();

 

        /// <summary>

        /// No Metadata Documentation available.

        /// </summary>

        [EdmScalarPropertyAttribute(EntityKeyProperty = false, IsNullable = false)]

        [DataMemberAttribute()]

        public global::System.String City

        {

            get

            {

                return _City;

            }

            set

            {

                OnCityChanging(value);

                ReportPropertyChanging("City");

                _City = StructuralObject.SetValidValue(value, false);

                ReportPropertyChanged("City");

                OnCityChanged();

            }

 

        }

        private global::System.String _City;

        partial void OnCityChanging(global::System.String value);

        partial void OnCityChanged();

 

        /// <summary>

        /// No Metadata Documentation available.

        /// </summary>

        [EdmScalarPropertyAttribute(EntityKeyProperty = false, IsNullable = false)]

        [DataMemberAttribute()]

        public global::System.String Region

        {

            get

            {

                return _Region;

            }

            set

            {

                OnRegionChanging(value);

                ReportPropertyChanging("Region");

                _Region = StructuralObject.SetValidValue(value, false);

                ReportPropertyChanged("Region");

                OnRegionChanged();

            }

 

        }

        private global::System.String _Region;

        partial void OnRegionChanging(global::System.String value);

        partial void OnRegionChanged();

 

        /// <summary>

        /// No Metadata Documentation available.

        /// </summary>

        [EdmScalarPropertyAttribute(EntityKeyProperty = false, IsNullable = false)]

        [DataMemberAttribute()]

        public global::System.String Country

        {

            get

            {

                return _Country;

            }

            set

            {

                OnCountryChanging(value);

                ReportPropertyChanging("Country");

                _Country = StructuralObject.SetValidValue(value, false);

                ReportPropertyChanged("Country");

                OnCountryChanged();

            }

 

        }

        private global::System.String _Country;

        partial void OnCountryChanging(global::System.String value);

        partial void OnCountryChanged();

 

        #endregion

    }

 

    #endregion

 

}

Pour avoir des entités POCO, il faut modifier ce template. C’est ce que j’ai fait.

Ainsi le code généré, est désormais le suivant :

using System;

using System.Data.Objects;

using System.Data.Objects.DataClasses;

using System.Data.EntityClient;

using System.ComponentModel;

using System.Xml.Serialization;

using System.Runtime.Serialization;

using System.Collections.Generic;

namespace ConsoleApplication1

{

    #region Contexts

    public interface ITestContainer

    {

        IObjectSet<Category> Categories { get; }

        IObjectSet<Product> Products { get; }

        IObjectSet<Supplier> Suppliers { get; }

    }

    /// <summary>

    /// No Metadata Documentation available.

    /// </summary>

    public partial class TestContainer : ObjectContext, ITestContainer

    {

        #region Constructors

        /// <summary>

        /// Initializes a new TestContainer object using the connection string found in the 'TestContainer' section of the application configuration file.

        /// </summary>

        public TestContainer()

            : base("name=TestContainer", "TestContainer")

        {

            OnContextCreated();

        }

 

        /// <summary>

        /// Initialize a new TestContainer object.

        /// </summary>

        public TestContainer(string connectionString)

            : base(connectionString, "TestContainer")

        {

            OnContextCreated();

        }

 

        /// <summary>

        /// Initialize a new TestContainer object.

        /// </summary>

        public TestContainer(EntityConnection connection)

            : base(connection, "TestContainer")

        {

            OnContextCreated();

        }

        #endregion

 

        #region Partial Methods

        partial void OnContextCreated();

        #endregion

 

        #region ObjectSet Properties

        /// <summary>

        /// No Metadata Documentation available.

        /// </summary>

        public ObjectSet<Category> Categories

        {

            get

            {

                if (_Categories == null)

                    _Categories = CreateObjectSet<Category>("Categories");

                return _Categories;

            }

        }

        private ObjectSet<Category> _Categories;

        IObjectSet<Category> ITestContainer.Categories { get { return Categories; } }

 

        /// <summary>

        /// No Metadata Documentation available.

        /// </summary>

        public ObjectSet<Product> Products

        {

            get

            {

                if (_Products == null)

                    _Products = CreateObjectSet<Product>("Products");

                return _Products;

            }

        }

        private ObjectSet<Product> _Products;

        IObjectSet<Product> ITestContainer.Products { get { return Products; } }

 

        /// <summary>

        /// No Metadata Documentation available.

        /// </summary>

        public ObjectSet<Supplier> Suppliers

        {

            get

            {

                if (_Suppliers == null)

                    _Suppliers = CreateObjectSet<Supplier>("Suppliers");

                return _Suppliers;

            }

        }

        private ObjectSet<Supplier> _Suppliers;

        IObjectSet<Supplier> ITestContainer.Suppliers { get { return Suppliers; } }

 

        #endregion

        #region AddTo Methods

 

        /// <summary>

        /// Deprecated Method for adding a new object to the Categories EntitySet. Consider using the .Add method of the associated ObjectSet&lt;T&gt; property instead.

        /// </summary>

        public void AddToCategories(Category category)

        {

            base.AddObject("Categories", category);

        }

 

        /// <summary>

        /// Deprecated Method for adding a new object to the Products EntitySet. Consider using the .Add method of the associated ObjectSet&lt;T&gt; property instead.

        /// </summary>

        public void AddToProducts(Product product)

        {

            base.AddObject("Products", product);

        }

 

        /// <summary>

        /// Deprecated Method for adding a new object to the Suppliers EntitySet. Consider using the .Add method of the associated ObjectSet&lt;T&gt; property instead.

        /// </summary>

        public void AddToSuppliers(Supplier supplier)

        {

            base.AddObject("Suppliers", supplier);

        }

        #endregion

    }

 

    #endregion

 

    #region Entities

    /// <summary>

    /// No Metadata Documentation available.

    /// </summary>

    [DataContractAttribute(IsReference = true)]

    public partial class Category

    {

        #region Primitive Properties

        /// <summary>

        /// No Metadata Documentation available.

        /// </summary>

        [DataMemberAttribute()]

        public Int32 Id { get; set; }

 

        /// <summary>

        /// No Metadata Documentation available.

        /// </summary>

        [DataMemberAttribute()]

        public virtual String Name { get; set; }

 

        /// <summary>

        /// No Metadata Documentation available.

        /// </summary>

        [DataMemberAttribute()]

        public virtual String Description { get; set; }

 

        #endregion

 

        #region Navigation Properties

        private List<Product> _products;

        [DataMemberAttribute()]

        /// <summary>

        /// No Metadata Documentation available.

        /// </summary>

        public virtual List<Product> Products

        {

            get

            {

                if (_products == null)

                    _products = new List<Product>();

                return _products;

            }

            set { _products = value; }

        }

 

        #endregion

    }

 

    /// <summary>

    /// No Metadata Documentation available.

    /// </summary>

    [DataContractAttribute(IsReference = true)]

    public partial class Product

    {

        #region Primitive Properties

        /// <summary>

        /// No Metadata Documentation available.

        /// </summary>

        [DataMemberAttribute()]

        public Int32 Id { get; set; }

 

        /// <summary>

        /// No Metadata Documentation available.

        /// </summary>

        [DataMemberAttribute()]

        public virtual String Name { get; set; }

 

        #endregion

 

        #region Navigation Properties

        /// <summary>

        /// No Metadata Documentation available.

        /// </summary>

        [DataMemberAttribute()]

        public virtual Category Category { get; set; }

 

        /// <summary>

        /// No Metadata Documentation available.

        /// </summary>

        [DataMemberAttribute()]

        public virtual Supplier Supplier { get; set; }

 

        #endregion

    }

 

    /// <summary>

    /// No Metadata Documentation available.

    /// </summary>

    [DataContractAttribute(IsReference = true)]

    public partial class Supplier

    {

        #region Primitive Properties

        /// <summary>

        /// No Metadata Documentation available.

        /// </summary>

        [DataMemberAttribute()]

        public Int32 Id { get; set; }

 

        /// <summary>

        /// No Metadata Documentation available.

        /// </summary>

        [DataMemberAttribute()]

        public virtual String CompanyName { get; set; }

 

        #endregion

        #region Complex Properties

 

        /// <summary>

        /// No Metadata Documentation available.

        /// </summary>

        [DataMemberAttribute()]

        public virtual Address Address { get; set; }

        #endregion

 

        #region Navigation Properties

        /// <summary>

        /// No Metadata Documentation available.

        /// </summary>

        [DataMemberAttribute()]

        private List<Product> _products;

        public virtual List<Product> Products

        {

            get

            {

                if (_products == null)

                    _products = new List<Product>();

                return _products;

            }

            set { _products = value; }

        }

 

        #endregion

    }

 

    #endregion

 

    #region ComplexTypes

    /// <summary>

    /// No Metadata Documentation available.

    /// </summary>

    [DataContractAttribute(IsReference = true)]

    public partial class Address

    {

        #region Primitive Properties

        /// <summary>

        /// No Metadata Documentation available.

        /// </summary>

        [DataMemberAttribute()]

        public virtual String AddressLine { get; set; }

 

        /// <summary>

        /// No Metadata Documentation available.

        /// </summary>

        [DataMemberAttribute()]

        public virtual String PostalCode { get; set; }

 

        /// <summary>

        /// No Metadata Documentation available.

        /// </summary>

        [DataMemberAttribute()]

        public virtual String City { get; set; }

 

        /// <summary>

        /// No Metadata Documentation available.

        /// </summary>

        [DataMemberAttribute()]

        public virtual String Region { get; set; }

 

        /// <summary>

        /// No Metadata Documentation available.

        /// </summary>

        [DataMemberAttribute()]

        public virtual String Country { get; set; }

 

        #endregion

    }

 

    #endregion

 

}

Premier point, l’interface ITestContainer, va me permettre de faire du mock afin de tester mes entités.

Deuxième point, les entités n’ont plus de lien avec EF.

Troisième point, à la manière d'NHibernate, le fait de déclarer une propriété virtual va permettre de bénéficier du tracking automatique des modifications.

Enfin, pour finir ce post, dans mes tests, j’ai utilisé une autre nouveauté d’EF4 : le lazy loading. Pour cela, il suffit de le spécifier dans les options du contexte :

context.ContextOptions.DeferredLoadingEnabled = true;

Enjoy Smile

Ce post vous a plu ? Ajoutez le dans vos favoris pour ne pas perdre de temps à le retrouver le jour où vous en aurez besoin :

Publié mercredi 20 mai 2009 17:42 par Matthieu MEZIL

Commentaires

# re: POCO, les joies du T4, la suite @ mardi 16 juin 2009 10:17

bonjour, le template POCO.tt appliqué à une petite hierarchie (classe A abstraite dont heritent 3 classes concretes B,C et D) genere dans POCO.cs un ObjectSet

<A> mais aucun pour les autres classes. Est-ce le comportement attendu ? Dans l'affirmative, quelle methode employer pour acceder aux objets  B,C ou D ?

digeo

# re: POCO, les joies du T4, la suite @ mardi 16 juin 2009 11:59

Oui c'est le comportement normal.

La propriété de type ObjectSet

<A> va renvoyer des A, des B, des C et des D.

Il est possible de ne récupérer que les B ou que les C ou que les D en utilisant la méthode OfType :

MonObjectSetDeA.OfType<B>() pour ne récupérer que les B par exemple.

Matthieu MEZIL

# re: POCO, les joies du T4, la suite @ mardi 16 juin 2009 12:33

Oui, j'avais depuis compris cela (je me forme à EF sur du béta, donc je suis ;-). Mais l'ajout necessaire d'une spécialisation OfType&lt;&gt; à chaque requete ne risque-t'il pas de pénaliser les performances, alors qu'un EntitySet par Type semble plus pratique (à manipuler en tout cas). Est-ce "par dedign" d'EF ?

digeo

# re: POCO, les joies du T4, la suite @ mardi 16 juin 2009 13:43

Non l'ajout d'un OfType n'impacte pas les perfs car il est directement traduit en SQL.

L'EntitySet sur la classe de base permet d'assurer l'intégrité des données.

Matthieu MEZIL

# re: POCO, les joies du T4, la suite @ mardi 16 juin 2009 23:16

Vous devriez regarder ceci.

Matthieu MEZIL

# re: POCO, les joies du T4, la suite @ lundi 26 juillet 2010 16:10

Bonjour Matthieu,

J'utilise actuellement EF4 avec T4 et j'ai un problème pour mes tests unitaires.

J'essaie de faire un mock de mon ObjectContext mais il reste très fortement lié aux données.

Pour retourner des entités j'instancie un ObjectContext avec ma chaîne de connexion et je crée des ObjectSet.

J'essaie d'ajouter de nouveaux objets à cet ObjectSet mais ils ne s'ajoutent pas. J'ai toujours mes entités provenant de la base de données.

Peut-on instancier un ObjectSet sans être lié aux données ?

Merci.

kewwwa

# re: POCO, les joies du T4, la suite @ lundi 26 juillet 2010 23:37

ObjectSet non mais pour ton mock, tu devrais utiliser ta propre classe qui implémente IObjectSet.

Hope that helps

Matthieu MEZIL

Les commentaires anonymes sont désactivés

Les 10 derniers blogs postés

- Merci par Blog de Jérémy Jeanson le 10-01-2019, 20:47

- Office 365: Script PowerShell pour auditer l’usage des Office Groups de votre tenant par Blog Technique de Romelard Fabrice le 04-26-2019, 11:02

- Office 365: Script PowerShell pour auditer l’usage de Microsoft Teams de votre tenant par Blog Technique de Romelard Fabrice le 04-26-2019, 10:39

- Office 365: Script PowerShell pour auditer l’usage de OneDrive for Business de votre tenant par Blog Technique de Romelard Fabrice le 04-25-2019, 15:13

- Office 365: Script PowerShell pour auditer l’usage de SharePoint Online de votre tenant par Blog Technique de Romelard Fabrice le 02-27-2019, 13:39

- Office 365: Script PowerShell pour auditer l’usage d’Exchange Online de votre tenant par Blog Technique de Romelard Fabrice le 02-25-2019, 15:07

- Office 365: Script PowerShell pour auditer le contenu de son Office 365 Stream Portal par Blog Technique de Romelard Fabrice le 02-21-2019, 17:56

- Office 365: Script PowerShell pour auditer le contenu de son Office 365 Video Portal par Blog Technique de Romelard Fabrice le 02-18-2019, 18:56

- Office 365: Script PowerShell pour extraire les Audit Log basés sur des filtres fournis par Blog Technique de Romelard Fabrice le 01-28-2019, 16:13

- SharePoint Online: Script PowerShell pour désactiver l’Option IRM des sites SPO non autorisés par Blog Technique de Romelard Fabrice le 12-14-2018, 13:01