Welcome to mirror list, hosted at ThFree Co, Russian Federation.

EntityProxyTypeInfo.cs « Internal « Objects « Data « System « System.Data.Entity « referencesource « class « mcs - github.com/mono/mono.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: a301deb03897dbc23b920deaf33bf80c677c9d7a (plain)
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
//---------------------------------------------------------------------
// <copyright file="EntityProxyTypeInfo.cs" company="Microsoft">
//      Copyright (c) Microsoft Corporation.  All rights reserved.
// </copyright>
//
// @owner       [....]
// @backupOwner [....]
//---------------------------------------------------------------------

namespace System.Data.Objects.Internal
{
    using System;
    using System.Collections.Generic;
    using System.Data.Metadata.Edm;
    using System.Diagnostics;
    using System.Linq;
    using System.Linq.Expressions;
    using System.Reflection;
    using System.Reflection.Emit;

    /// <summary>
    /// Contains the Type of a proxy class, along with any behaviors associated with that proxy Type.
    /// </summary>
    internal sealed class EntityProxyTypeInfo
    {
        private readonly Type _proxyType;
        private readonly ClrEntityType _entityType;        // The OSpace entity type that created this proxy info

        internal const string EntityWrapperFieldName = "_entityWrapper";
        private const string InitializeEntityCollectionsName = "InitializeEntityCollections";
        private readonly DynamicMethod _initializeCollections;

        private readonly Func<object, string, object> _baseGetter;
        private readonly HashSet<string> _propertiesWithBaseGetter;
        private readonly Action<object, string, object> _baseSetter;
        private readonly HashSet<string> _propertiesWithBaseSetter;
        private readonly Func<object, object> Proxy_GetEntityWrapper;
        private readonly Func<object, object, object> Proxy_SetEntityWrapper; // IEntityWrapper Func(object proxy, IEntityWrapper value)

        private readonly Func<object> _createObject;

        // An index of relationship metadata strings to an AssociationType
        // This is used when metadata is not otherwise available to the proxy
        private readonly Dictionary<Tuple<string, string>, AssociationType> _navigationPropertyAssociationTypes;

        internal EntityProxyTypeInfo(Type proxyType, ClrEntityType ospaceEntityType, DynamicMethod initializeCollections, List<PropertyInfo> baseGetters, List<PropertyInfo> baseSetters)
        {
            Debug.Assert(proxyType != null, "proxyType must be non-null");

            _proxyType = proxyType;
            _entityType = ospaceEntityType;

            _initializeCollections = initializeCollections;

            _navigationPropertyAssociationTypes = new Dictionary<Tuple<string, string>, AssociationType>();
            foreach (NavigationProperty navigationProperty in ospaceEntityType.NavigationProperties)
            {
                _navigationPropertyAssociationTypes.Add(
                    new Tuple<string, string>(
                        navigationProperty.RelationshipType.FullName,
                        navigationProperty.ToEndMember.Name),
                    (AssociationType)navigationProperty.RelationshipType);

                if (navigationProperty.RelationshipType.Name != navigationProperty.RelationshipType.FullName)
                {
                    // Sometimes there isn't enough metadata to have a container name
                    // Default codegen doesn't qualify names
                    _navigationPropertyAssociationTypes.Add(
                        new Tuple<string, string>(
                            navigationProperty.RelationshipType.Name,
                            navigationProperty.ToEndMember.Name),
                        (AssociationType)navigationProperty.RelationshipType);
                }
            }

            FieldInfo entityWrapperField = proxyType.GetField(EntityWrapperFieldName, BindingFlags.DeclaredOnly | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);

            ParameterExpression Object_Parameter = Expression.Parameter(typeof(object), "proxy");
            ParameterExpression Value_Parameter = Expression.Parameter(typeof(object), "value");

            Debug.Assert(entityWrapperField != null, "entityWrapperField does not exist");   

            // Create the Wrapper Getter
            Expression<Func<object, object>> lambda = Expression.Lambda<Func<object, object>>(
                    Expression.Field(
                        Expression.Convert(Object_Parameter, entityWrapperField.DeclaringType), entityWrapperField),
                        Object_Parameter);
            Func<object, object> getEntityWrapperDelegate = lambda.Compile();
            Proxy_GetEntityWrapper = (object proxy) =>
            {
                // This code validates that the wrapper points to the proxy that holds the wrapper.
                // This guards against mischief by switching this wrapper out for another one obtained
                // from a different object.
                IEntityWrapper wrapper = ((IEntityWrapper)getEntityWrapperDelegate(proxy));
                if (wrapper != null && !object.ReferenceEquals(wrapper.Entity, proxy))
                {
                    throw new InvalidOperationException(System.Data.Entity.Strings.EntityProxyTypeInfo_ProxyHasWrongWrapper);
                }
                return wrapper;
            };

            // Create the Wrapper setter
            Proxy_SetEntityWrapper = Expression.Lambda<Func<object, object, object>>(
                    Expression.Assign(
                        Expression.Field(
                            Expression.Convert(Object_Parameter, entityWrapperField.DeclaringType),
                            entityWrapperField),
                        Value_Parameter),
                    Object_Parameter, Value_Parameter).Compile();


            ParameterExpression PropertyName_Parameter = Expression.Parameter(typeof(string), "propertyName");
            MethodInfo baseGetterMethod = proxyType.GetMethod("GetBasePropertyValue", BindingFlags.Public | BindingFlags.Instance, null, new Type[] { typeof(string) }, null);
            if (baseGetterMethod != null)
            {
                _baseGetter = Expression.Lambda<Func<object, string, object>>(
                    Expression.Call(Expression.Convert(Object_Parameter, proxyType), baseGetterMethod, PropertyName_Parameter),
                    Object_Parameter, PropertyName_Parameter).Compile();
            }

            ParameterExpression PropertyValue_Parameter = Expression.Parameter(typeof(object), "propertyName");
            MethodInfo baseSetterMethod = proxyType.GetMethod("SetBasePropertyValue", BindingFlags.Public | BindingFlags.Instance, null, new Type[] { typeof(string), typeof(object) }, null);
            if (baseSetterMethod != null)
            {
                _baseSetter = Expression.Lambda<Action<object, string, object>>(
                        Expression.Call(Expression.Convert(Object_Parameter, proxyType), baseSetterMethod, PropertyName_Parameter, PropertyValue_Parameter),
                        Object_Parameter, PropertyName_Parameter, PropertyValue_Parameter).Compile();
            }

            _propertiesWithBaseGetter = new HashSet<string>(baseGetters.Select(p => p.Name));
            _propertiesWithBaseSetter = new HashSet<string>(baseSetters.Select(p => p.Name));

            _createObject = LightweightCodeGenerator.CreateConstructor(proxyType) as Func<object>;
        }

        internal object CreateProxyObject()
        {
            return _createObject();
        }

        internal Type ProxyType
        {
            get { return _proxyType; }
        }

        internal DynamicMethod InitializeEntityCollections
        {
            get { return _initializeCollections; }
        }

        public Func<object, string, object> BaseGetter
        {
            get { return _baseGetter; }
        }

        public bool ContainsBaseGetter(string propertyName)
        {
            return BaseGetter != null && _propertiesWithBaseGetter.Contains(propertyName);
        }

        public bool ContainsBaseSetter(string propertyName)
        {
            return BaseSetter != null && _propertiesWithBaseSetter.Contains(propertyName);
        }

        public Action<object, string, object> BaseSetter
        {
            get { return _baseSetter; }
        }

        public bool TryGetNavigationPropertyAssociationType(string relationshipName, string targetRoleName, out AssociationType associationType)
        {
            return _navigationPropertyAssociationTypes.TryGetValue(new Tuple<string, string>(relationshipName, targetRoleName), out associationType);
        }

        public void ValidateType(ClrEntityType ospaceEntityType)
        {
            if (ospaceEntityType != _entityType && ospaceEntityType.HashedDescription != _entityType.HashedDescription)
            {
                Debug.Assert(ospaceEntityType.ClrType == _entityType.ClrType);
                throw EntityUtil.DuplicateTypeForProxyType(ospaceEntityType.ClrType);
            }
        }

        #region Wrapper on the Proxy

        /// <summary>
        /// Set the proxy object's private entity wrapper field value to the specified entity wrapper object.
        /// The proxy object (representing the wrapped entity) is retrieved from the wrapper itself.
        /// </summary>
        /// <param name="wrapper">Wrapper object to be referenced by the proxy.</param>
        /// <returns>
        /// The supplied entity wrapper.
        /// This is done so that this method can be more easily composed within lambda expressions (such as in the materializer).
        /// </returns>
        internal IEntityWrapper SetEntityWrapper(IEntityWrapper wrapper)
        {
            Debug.Assert(wrapper != null, "wrapper must be non-null");
            Debug.Assert(wrapper.Entity != null, "proxy must be non-null");
            return Proxy_SetEntityWrapper(wrapper.Entity, wrapper) as IEntityWrapper;
        }

        /// <summary>
        /// Gets the proxy object's entity wrapper field value
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        internal IEntityWrapper GetEntityWrapper(object entity)
        {
            return Proxy_GetEntityWrapper(entity) as IEntityWrapper;
        }

        internal Func<object, object> EntityWrapperDelegate
        {
            get { return Proxy_GetEntityWrapper; }
        }

        #endregion
    }
}