MappedMetaModel.cs 76 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Collections.ObjectModel;
  5. using System.Linq.Expressions;
  6. using System.Reflection;
  7. using System.Text;
  8. using System.Linq;
  9. using System.Data.Linq.Provider;
  10. using System.Data.Linq.Mapping;
  11. using System.Data.Linq.SqlClient;
  12. using System.Threading;
  13. using System.Runtime.Versioning;
  14. using LinqToSqlShared.Mapping;
  15. using System.Runtime.CompilerServices;
  16. namespace System.Data.Linq.Mapping {
  17. internal class MappedMetaModel : MetaModel {
  18. ReaderWriterLock @lock = new ReaderWriterLock();
  19. MappingSource mappingSource;
  20. Type contextType;
  21. Type providerType;
  22. DatabaseMapping mapping;
  23. HashSet<Module> modules;
  24. Dictionary<string, Type> types;
  25. Dictionary<Type, MetaType> metaTypes;
  26. Dictionary<Type, MetaTable> metaTables;
  27. Dictionary<MetaPosition, MetaFunction> metaFunctions;
  28. bool fullyLoaded;
  29. [ResourceExposure(ResourceScope.Assembly | ResourceScope.Machine)] // mapping parameter contains various type references.
  30. [ResourceConsumption(ResourceScope.Assembly | ResourceScope.Machine)] // FindType method call.
  31. internal MappedMetaModel(MappingSource mappingSource, Type contextType, DatabaseMapping mapping) {
  32. this.mappingSource = mappingSource;
  33. this.contextType = contextType;
  34. this.mapping = mapping;
  35. this.modules = new HashSet<Module>();
  36. this.modules.Add(this.contextType.Module);
  37. this.metaTypes = new Dictionary<Type, MetaType>();
  38. this.metaTables = new Dictionary<Type, MetaTable>();
  39. this.types = new Dictionary<string, Type>();
  40. // Provider type
  41. if (this.providerType == null && !String.IsNullOrEmpty(this.mapping.Provider)) {
  42. this.providerType = this.FindType(this.mapping.Provider, typeof(SqlProvider).Namespace);
  43. if (this.providerType == null) {
  44. throw Error.ProviderTypeNotFound(this.mapping.Provider);
  45. }
  46. }
  47. else if (this.providerType == null) {
  48. this.providerType = typeof(SqlProvider);
  49. }
  50. this.Init();
  51. }
  52. #region Initialization
  53. private void Init() {
  54. if (!fullyLoaded) {
  55. // The fullyLoaded state is required so that tools like
  56. // CreateDatabase can get a full view of all tables.
  57. @lock.AcquireWriterLock(Timeout.Infinite);
  58. try {
  59. if (!fullyLoaded) {
  60. // Initialize static tables and functions.
  61. this.InitStaticTables();
  62. this.InitFunctions();
  63. fullyLoaded = true;
  64. }
  65. }
  66. finally {
  67. @lock.ReleaseWriterLock();
  68. }
  69. }
  70. }
  71. [ResourceExposure(ResourceScope.None)] // Exposure is via external mapping file/attributes.
  72. [ResourceConsumption(ResourceScope.Assembly | ResourceScope.Machine, ResourceScope.Assembly | ResourceScope.Machine)] // FindType method call.
  73. private void InitStaticTables() {
  74. this.InitStaticTableTypes();
  75. foreach (TableMapping tableMapping in this.mapping.Tables) {
  76. Type rowType = this.FindType(tableMapping.RowType.Name);
  77. if (rowType == null) {
  78. throw Error.CouldNotFindTypeFromMapping(tableMapping.RowType.Name);
  79. }
  80. Type rootType = this.GetRootType(rowType, tableMapping.RowType);
  81. MetaTable table = new MappedTable(this, tableMapping, rootType);
  82. foreach (MetaType mt in table.RowType.InheritanceTypes) {
  83. this.metaTypes.Add(mt.Type, mt);
  84. this.metaTables.Add(mt.Type, table);
  85. }
  86. }
  87. }
  88. private void InitStaticTableTypes() {
  89. for (Type type = this.contextType; type != typeof(DataContext); type = type.BaseType) {
  90. FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly);
  91. foreach (FieldInfo fi in fields) {
  92. Type ft = fi.FieldType;
  93. if (ft.IsGenericType && ft.GetGenericTypeDefinition() == typeof(Table<>)) {
  94. Type rowType = ft.GetGenericArguments()[0];
  95. if (!this.types.ContainsKey(rowType.Name)) {
  96. this.types.Add(rowType.FullName, rowType);
  97. if (!this.types.ContainsKey(rowType.Name)) {
  98. this.types.Add(rowType.Name, rowType);
  99. }
  100. this.modules.Add(rowType.Module);
  101. }
  102. }
  103. }
  104. PropertyInfo[] props = type.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly);
  105. foreach (PropertyInfo pi in props) {
  106. Type pt = pi.PropertyType;
  107. if (pt.IsGenericType && pt.GetGenericTypeDefinition() == typeof(Table<>)) {
  108. Type rowType = pt.GetGenericArguments()[0];
  109. if (!this.types.ContainsKey(rowType.Name)) {
  110. this.types.Add(rowType.FullName, rowType);
  111. if (!this.types.ContainsKey(rowType.Name)) {
  112. this.types.Add(rowType.Name, rowType);
  113. }
  114. this.modules.Add(rowType.Module);
  115. }
  116. }
  117. }
  118. }
  119. }
  120. [ResourceExposure(ResourceScope.None)] // mapping instance variable is set elsewhere.
  121. [ResourceConsumption(ResourceScope.Assembly | ResourceScope.Machine, ResourceScope.Assembly | ResourceScope.Machine)] // For GetMethods call.
  122. private void InitFunctions() {
  123. this.metaFunctions = new Dictionary<MetaPosition, MetaFunction>();
  124. if (this.contextType != typeof(DataContext)) {
  125. foreach (FunctionMapping fmap in this.mapping.Functions) {
  126. MethodInfo method = this.GetMethod(fmap.MethodName);
  127. if (method == null) {
  128. throw Error.MethodCannotBeFound(fmap.MethodName);
  129. }
  130. MappedFunction func = new MappedFunction(this, fmap, method);
  131. this.metaFunctions.Add(new MetaPosition(method), func);
  132. // pre-set all known function result types into metaType map
  133. foreach (MetaType rt in func.ResultRowTypes) {
  134. foreach (MetaType it in rt.InheritanceTypes) {
  135. if (!this.metaTypes.ContainsKey(it.Type)) {
  136. this.metaTypes.Add(it.Type, it);
  137. }
  138. }
  139. }
  140. }
  141. }
  142. }
  143. #endregion
  144. public override MappingSource MappingSource {
  145. get { return this.mappingSource; }
  146. }
  147. public override Type ContextType {
  148. get { return this.contextType; }
  149. }
  150. public override string DatabaseName {
  151. get { return this.mapping.DatabaseName; }
  152. }
  153. public override Type ProviderType {
  154. get { return this.providerType; }
  155. }
  156. public override IEnumerable<MetaTable> GetTables() {
  157. return this.metaTables.Values.Where(x => x != null).Distinct();
  158. }
  159. public override MetaTable GetTable(Type rowType) {
  160. if (rowType == null) {
  161. throw Error.ArgumentNull("rowType");
  162. }
  163. MetaTable table = null;
  164. this.metaTables.TryGetValue(rowType, out table);
  165. return table;
  166. }
  167. public override MetaType GetMetaType(Type type) {
  168. if (type == null) {
  169. throw Error.ArgumentNull("type");
  170. }
  171. MetaType mtype = null;
  172. @lock.AcquireReaderLock(Timeout.Infinite);
  173. try {
  174. if (this.metaTypes.TryGetValue(type, out mtype)) {
  175. return mtype;
  176. }
  177. }
  178. finally {
  179. @lock.ReleaseReaderLock();
  180. }
  181. @lock.AcquireWriterLock(Timeout.Infinite);
  182. try {
  183. if (!this.metaTypes.TryGetValue(type, out mtype)) {
  184. // not known, so must be unmapped type
  185. mtype = new UnmappedType(this, type);
  186. this.metaTypes.Add(type, mtype);
  187. }
  188. }
  189. finally {
  190. @lock.ReleaseWriterLock();
  191. }
  192. return mtype;
  193. }
  194. public override MetaFunction GetFunction(MethodInfo method) {
  195. if (method == null) {
  196. throw new ArgumentNullException("method");
  197. }
  198. MetaFunction func = null;
  199. this.metaFunctions.TryGetValue(new MetaPosition(method), out func);
  200. return func;
  201. }
  202. public override IEnumerable<MetaFunction> GetFunctions() {
  203. return this.metaFunctions.Values;
  204. }
  205. private Type GetRootType(Type type, TypeMapping rootMapping) {
  206. if (string.Compare(rootMapping.Name, type.Name, StringComparison.Ordinal) == 0
  207. || string.Compare(rootMapping.Name, type.FullName, StringComparison.Ordinal) == 0
  208. || string.Compare(rootMapping.Name, type.AssemblyQualifiedName, StringComparison.Ordinal) == 0)
  209. return type;
  210. if (type.BaseType != typeof(object)) {
  211. return this.GetRootType(type.BaseType, rootMapping);
  212. }
  213. throw Error.UnableToResolveRootForType(type);
  214. }
  215. [ResourceExposure(ResourceScope.Assembly | ResourceScope.Machine)] // name parameter will be found on a type.
  216. [ResourceConsumption(ResourceScope.Assembly | ResourceScope.Machine)] // FindType method call.
  217. private MethodInfo GetMethod(string name) {
  218. string typeName, methodName;
  219. this.GetTypeAndMethod(name, out typeName, out methodName);
  220. Type type = this.FindType(typeName);
  221. if (type != null) {
  222. return type.GetMethod(methodName, BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic);
  223. }
  224. return null;
  225. }
  226. private void GetTypeAndMethod(string name, out string typeName, out string methodName) {
  227. int dotIndex = name.LastIndexOf(".", StringComparison.CurrentCulture);
  228. if (dotIndex > 0) {
  229. typeName = name.Substring(0, dotIndex);
  230. methodName = name.Substring(dotIndex + 1);
  231. }
  232. else {
  233. typeName = this.contextType.FullName;
  234. methodName = name;
  235. }
  236. }
  237. [ResourceExposure(ResourceScope.Assembly | ResourceScope.Machine)] // name parameter is a type name.
  238. [ResourceConsumption(ResourceScope.Assembly | ResourceScope.Machine)] // FindType method call.
  239. internal Type FindType(string name) {
  240. return this.FindType(name, this.contextType.Namespace);
  241. }
  242. [ResourceExposure(ResourceScope.Assembly | ResourceScope.Machine)] // name parameter is a type name.
  243. [ResourceConsumption(ResourceScope.Assembly | ResourceScope.Machine)] // SearchForType method call.
  244. internal Type FindType(string name, string defaultNamespace) {
  245. Type result = null;
  246. string name2 = null;
  247. @lock.AcquireReaderLock(Timeout.Infinite);
  248. try {
  249. if (this.types.TryGetValue(name, out result)) {
  250. return result;
  251. }
  252. name2 = name.Contains(".") ? null : defaultNamespace + "." + name;
  253. if (name2 != null && this.types.TryGetValue(name2, out result)) {
  254. return result;
  255. }
  256. }
  257. finally {
  258. @lock.ReleaseReaderLock();
  259. }
  260. // don't block anyone while we search for the correct type
  261. Type foundResult = this.SearchForType(name);
  262. if (foundResult == null && name2 != null) {
  263. foundResult = this.SearchForType(name2);
  264. }
  265. if (foundResult != null) {
  266. @lock.AcquireWriterLock(Timeout.Infinite);
  267. try {
  268. if (this.types.TryGetValue(name, out result)) {
  269. return result;
  270. }
  271. this.types.Add(name, foundResult);
  272. return foundResult;
  273. }
  274. finally {
  275. @lock.ReleaseWriterLock();
  276. }
  277. }
  278. return null;
  279. }
  280. [ResourceExposure(ResourceScope.Assembly | ResourceScope.Machine)] // name parameter is a type name.
  281. [ResourceConsumption(ResourceScope.Assembly | ResourceScope.Machine)] // SearchForType method call.
  282. private Type SearchForType(string name) {
  283. // Try search for type using case sensitive.
  284. Type type = SearchForType(name, false);
  285. if (type != null) {
  286. return type;
  287. }
  288. // Try search for type using case in-sensitive.
  289. return SearchForType(name, true);
  290. }
  291. [ResourceExposure(ResourceScope.Assembly | ResourceScope.Machine)] // name parameter is a type name.
  292. [ResourceConsumption(ResourceScope.Assembly | ResourceScope.Machine)] // Assembly.GetLoadedModules method call.
  293. private Type SearchForType(string name, bool ignoreCase) {
  294. // first try default system lookup
  295. Type type = Type.GetType(name, false, ignoreCase);
  296. if (type != null) {
  297. return type;
  298. }
  299. // try all known modules (modules that other statically known types were found in)
  300. foreach (Module module in this.modules) {
  301. type = module.GetType(name, false, ignoreCase);
  302. if (type != null) {
  303. return type;
  304. }
  305. }
  306. // try all loaded modules (is there a better way?)
  307. foreach (Assembly a in AppDomain.CurrentDomain.GetAssemblies()) {
  308. foreach (Module module in a.GetLoadedModules()) {
  309. type = module.GetType(name, false, ignoreCase);
  310. if (type != null) {
  311. return type;
  312. }
  313. }
  314. }
  315. return null;
  316. }
  317. }
  318. internal sealed class MappedTable : MetaTable {
  319. MappedMetaModel model;
  320. TableMapping mapping;
  321. MetaType rowType;
  322. bool hasMethods;
  323. MethodInfo insertMethod;
  324. MethodInfo updateMethod;
  325. MethodInfo deleteMethod;
  326. [ResourceExposure(ResourceScope.Assembly | ResourceScope.Machine)] // Parameter contains various type references.
  327. [ResourceConsumption(ResourceScope.Assembly | ResourceScope.Machine)] // MappedRootType constructor call.
  328. internal MappedTable(MappedMetaModel model, TableMapping mapping, Type rowType) {
  329. this.model = model;
  330. this.mapping = mapping;
  331. this.rowType = new MappedRootType(model, this, mapping.RowType, rowType);
  332. }
  333. public override MetaModel Model {
  334. get { return this.model; }
  335. }
  336. public override string TableName {
  337. get { return this.mapping.TableName; }
  338. }
  339. public override MetaType RowType {
  340. get { return this.rowType; }
  341. }
  342. public override MethodInfo InsertMethod {
  343. get {
  344. this.InitMethods();
  345. return this.insertMethod;
  346. }
  347. }
  348. public override MethodInfo UpdateMethod {
  349. get {
  350. this.InitMethods();
  351. return this.updateMethod;
  352. }
  353. }
  354. public override MethodInfo DeleteMethod {
  355. get {
  356. this.InitMethods();
  357. return this.deleteMethod;
  358. }
  359. }
  360. private void InitMethods() {
  361. if (!this.hasMethods) {
  362. this.insertMethod = MethodFinder.FindMethod(
  363. this.model.ContextType,
  364. "Insert" + rowType.Name,
  365. BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic,
  366. new Type[] { rowType.Type }
  367. );
  368. this.updateMethod = MethodFinder.FindMethod(
  369. this.model.ContextType,
  370. "Update" + rowType.Name,
  371. BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic,
  372. new Type[] { rowType.Type }
  373. );
  374. this.deleteMethod = MethodFinder.FindMethod(
  375. this.model.ContextType,
  376. "Delete" + rowType.Name,
  377. BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic,
  378. new Type[] { rowType.Type }
  379. );
  380. this.hasMethods = true;
  381. }
  382. }
  383. }
  384. internal sealed class MappedRootType : MappedType {
  385. Dictionary<Type, MetaType> derivedTypes;
  386. Dictionary<object, MetaType> inheritanceCodes;
  387. ReadOnlyCollection<MetaType> inheritanceTypes;
  388. MetaType inheritanceDefault;
  389. bool hasInheritance;
  390. [ResourceExposure(ResourceScope.Assembly | ResourceScope.Machine)] // Various parameters can contain type names.
  391. [ResourceConsumption(ResourceScope.Assembly | ResourceScope.Machine)] // InitInheritedType method call.
  392. public MappedRootType(MappedMetaModel model, MappedTable table, TypeMapping typeMapping, Type type)
  393. : base(model, table, typeMapping, type, null) {
  394. if (typeMapping == null)
  395. throw Error.ArgumentNull("typeMapping");
  396. if (typeMapping.InheritanceCode != null || typeMapping.DerivedTypes.Count > 0) {
  397. if (this.Discriminator == null) {
  398. throw Error.NoDiscriminatorFound(type.Name);
  399. }
  400. this.hasInheritance = true;
  401. if (!MappingSystem.IsSupportedDiscriminatorType(this.Discriminator.Type)) {
  402. throw Error.DiscriminatorClrTypeNotSupported(this.Discriminator.DeclaringType.Name, this.Discriminator.Name, this.Discriminator.Type);
  403. }
  404. this.derivedTypes = new Dictionary<Type, MetaType>();
  405. this.inheritanceCodes = new Dictionary<object, MetaType>();
  406. this.InitInheritedType(typeMapping, this);
  407. }
  408. if (this.inheritanceDefault == null && (this.inheritanceCode != null || this.inheritanceCodes != null && this.inheritanceCodes.Count > 0))
  409. throw Error.InheritanceHierarchyDoesNotDefineDefault(type);
  410. if (this.derivedTypes != null) {
  411. this.inheritanceTypes = this.derivedTypes.Values.ToList().AsReadOnly();
  412. }
  413. else {
  414. this.inheritanceTypes = new MetaType[] { this }.ToList().AsReadOnly();
  415. }
  416. this.Validate();
  417. }
  418. private void Validate() {
  419. Dictionary<object, string> memberToColumn = new Dictionary<object, string>();
  420. foreach (MetaType type in this.InheritanceTypes) {
  421. // NB: Table node in XML can have only one Type node -- enforced by XSD
  422. foreach (MetaDataMember mem in type.PersistentDataMembers) {
  423. if (mem.IsDeclaredBy(type)) {
  424. if (mem.IsDiscriminator && !this.HasInheritance) {
  425. throw Error.NonInheritanceClassHasDiscriminator(type);
  426. }
  427. if (!mem.IsAssociation) {
  428. // validate that no database column is mapped twice
  429. if (!string.IsNullOrEmpty(mem.MappedName)) {
  430. string column;
  431. object dn = InheritanceRules.DistinguishedMemberName(mem.Member);
  432. if (memberToColumn.TryGetValue(dn, out column)) {
  433. if (column != mem.MappedName) {
  434. throw Error.MemberMappedMoreThanOnce(mem.Member.Name);
  435. }
  436. }
  437. else {
  438. memberToColumn.Add(dn, mem.MappedName);
  439. }
  440. }
  441. }
  442. }
  443. }
  444. }
  445. }
  446. [ResourceExposure(ResourceScope.Assembly | ResourceScope.Machine)] // typeMap parameter's Name property.
  447. [ResourceConsumption(ResourceScope.Assembly | ResourceScope.Machine)] // FindType method call.
  448. private MetaType InitDerivedTypes(TypeMapping typeMap) {
  449. Type type = ((MappedMetaModel)Model).FindType(typeMap.Name);
  450. if (type == null)
  451. throw Error.CouldNotFindRuntimeTypeForMapping(typeMap.Name);
  452. MappedType rowType = new MappedType(this.Model, this.Table, typeMap, type, this);
  453. return this.InitInheritedType(typeMap, rowType);
  454. }
  455. [ResourceExposure(ResourceScope.Assembly | ResourceScope.Machine)] // typeMap parameter's Name property.
  456. [ResourceConsumption(ResourceScope.Assembly | ResourceScope.Machine)] // InitDerivedTypes method call.
  457. private MetaType InitInheritedType(TypeMapping typeMap, MappedType type) {
  458. this.derivedTypes.Add(type.Type, type);
  459. if (typeMap.InheritanceCode != null) { // Mapping with no inheritance code: For example, an unmapped intermediate class in a hierarchy.
  460. if (this.Discriminator == null)
  461. throw Error.NoDiscriminatorFound(type.Name);
  462. if (type.Type.IsAbstract)
  463. throw Error.AbstractClassAssignInheritanceDiscriminator(type.Type);
  464. object keyValue = DBConvert.ChangeType(typeMap.InheritanceCode, this.Discriminator.Type);
  465. foreach (object d in inheritanceCodes.Keys) {
  466. // if the keys are equal, or if they are both strings containing only spaces
  467. // they are considered equal
  468. if ((keyValue.GetType() == typeof(string) && ((string)keyValue).Trim().Length == 0 &&
  469. d.GetType() == typeof(string) && ((string)d).Trim().Length == 0) ||
  470. object.Equals(d, keyValue)) {
  471. throw Error.InheritanceCodeUsedForMultipleTypes(keyValue);
  472. }
  473. }
  474. if (type.inheritanceCode != null)
  475. throw Error.InheritanceTypeHasMultipleDiscriminators(type);
  476. type.inheritanceCode = keyValue;
  477. this.inheritanceCodes.Add(keyValue, type);
  478. if (typeMap.IsInheritanceDefault) {
  479. if (this.inheritanceDefault != null)
  480. throw Error.InheritanceTypeHasMultipleDefaults(type);
  481. this.inheritanceDefault = type;
  482. }
  483. }
  484. // init sub-inherited types
  485. foreach (TypeMapping tm in typeMap.DerivedTypes) {
  486. this.InitDerivedTypes(tm);
  487. }
  488. return type;
  489. }
  490. public override bool HasInheritance {
  491. get { return this.hasInheritance; }
  492. }
  493. public override bool HasInheritanceCode {
  494. get { return this.InheritanceCode != null; }
  495. }
  496. public override ReadOnlyCollection<MetaType> InheritanceTypes {
  497. get { return this.inheritanceTypes; }
  498. }
  499. public override MetaType GetInheritanceType(Type type) {
  500. if (type == this.Type)
  501. return this;
  502. MetaType metaType = null;
  503. if (this.derivedTypes != null) {
  504. this.derivedTypes.TryGetValue(type, out metaType);
  505. }
  506. return metaType;
  507. }
  508. public override MetaType InheritanceDefault {
  509. get { return this.inheritanceDefault; }
  510. }
  511. }
  512. internal class MappedType : MetaType {
  513. MetaModel model;
  514. MetaTable table;
  515. Type type;
  516. TypeMapping typeMapping;
  517. Dictionary<object, MetaDataMember> dataMemberMap;
  518. ReadOnlyCollection<MetaDataMember> dataMembers;
  519. ReadOnlyCollection<MetaDataMember> persistentDataMembers;
  520. ReadOnlyCollection<MetaDataMember> identities;
  521. MetaDataMember dbGeneratedIdentity;
  522. MetaDataMember version;
  523. MetaDataMember discriminator;
  524. MetaType inheritanceRoot;
  525. bool inheritanceBaseSet;
  526. MetaType inheritanceBase;
  527. internal object inheritanceCode;
  528. ReadOnlyCollection<MetaType> derivedTypes;
  529. ReadOnlyCollection<MetaAssociation> associations;
  530. bool hasMethods;
  531. bool hasAnyLoadMethod;
  532. bool hasAnyValidateMethod;
  533. MethodInfo onLoadedMethod;
  534. MethodInfo onValidateMethod;
  535. object locktarget = new object(); // Hold locks on private object rather than public MetaType.
  536. internal MappedType(MetaModel model, MetaTable table, TypeMapping typeMapping, Type type, MetaType inheritanceRoot) {
  537. this.model = model;
  538. this.table = table;
  539. this.typeMapping = typeMapping;
  540. this.type = type;
  541. this.inheritanceRoot = inheritanceRoot != null ? inheritanceRoot : this;
  542. this.InitDataMembers();
  543. this.identities = this.dataMembers.Where(m => m.IsPrimaryKey).ToList().AsReadOnly();
  544. this.persistentDataMembers = this.dataMembers.Where(m => m.IsPersistent).ToList().AsReadOnly();
  545. }
  546. #region Initialization
  547. private void ValidatePrimaryKeyMember(MetaDataMember mm) {
  548. //if the type is a sub-type, no member in the type can be primary key
  549. if (mm.IsPrimaryKey && this.inheritanceRoot != this && mm.Member.DeclaringType == this.type) {
  550. throw (Error.PrimaryKeyInSubTypeNotSupported(this.type.Name, mm.Name));
  551. }
  552. }
  553. private void InitMethods() {
  554. if (!this.hasMethods) {
  555. this.onLoadedMethod = MethodFinder.FindMethod(
  556. this.Type,
  557. "OnLoaded",
  558. BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic,
  559. Type.EmptyTypes,
  560. false
  561. );
  562. this.onValidateMethod = MethodFinder.FindMethod(
  563. this.Type,
  564. "OnValidate",
  565. BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic,
  566. new[] { typeof(ChangeAction) },
  567. false
  568. );
  569. this.hasAnyLoadMethod = (this.onLoadedMethod != null) || (this.InheritanceBase != null && this.InheritanceBase.HasAnyLoadMethod);
  570. this.hasAnyValidateMethod = (this.onValidateMethod != null) || (this.InheritanceBase != null && this.InheritanceBase.HasAnyValidateMethod);
  571. this.hasMethods = true;
  572. }
  573. }
  574. private void InitDataMembers() {
  575. if (this.dataMembers == null) {
  576. Dictionary<object, MetaDataMember> map = new Dictionary<object, MetaDataMember>();
  577. List<MetaDataMember> dMembers = new List<MetaDataMember>();
  578. int ordinal = 0;
  579. BindingFlags flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy;
  580. // Map of valid mapped names.
  581. Dictionary<string, MemberMapping> names = new Dictionary<string, MemberMapping>();
  582. Type currentType = this.type;
  583. for (TypeMapping tm = this.typeMapping; tm != null; tm = tm.BaseType) {
  584. foreach (MemberMapping mmap in tm.Members) {
  585. names[mmap.MemberName + ":" + currentType.Name] = mmap;
  586. }
  587. currentType = currentType.BaseType;
  588. }
  589. HashSet<string> namesSeen = new HashSet<string>(); // Keep track of which names from the mapping file have been seen.
  590. FieldInfo[] fis = TypeSystem.GetAllFields(this.type, flags).ToArray();
  591. if (fis != null) {
  592. foreach (FieldInfo fi in fis) {
  593. MemberMapping mmap;
  594. string name = fi.Name + ":" + fi.DeclaringType.Name;
  595. if (names.TryGetValue(name, out mmap)) {
  596. namesSeen.Add(name);
  597. object dn = InheritanceRules.DistinguishedMemberName(fi);
  598. MetaDataMember mm;
  599. if (!map.TryGetValue(dn, out mm)) {
  600. mm = new MappedDataMember(this, fi, mmap, ordinal);
  601. map.Add(InheritanceRules.DistinguishedMemberName(mm.Member), mm);
  602. dMembers.Add(mm);
  603. this.InitSpecialMember(mm);
  604. }
  605. ValidatePrimaryKeyMember(mm);
  606. ordinal++;
  607. }
  608. }
  609. }
  610. PropertyInfo[] pis = TypeSystem.GetAllProperties(this.type, flags).ToArray();
  611. if (pis != null) {
  612. foreach (PropertyInfo pi in pis) {
  613. MemberMapping mmap;
  614. string name = pi.Name + ":" + pi.DeclaringType.Name;
  615. if (names.TryGetValue(name, out mmap)) {
  616. namesSeen.Add(name);
  617. MetaDataMember mm;
  618. object dn = InheritanceRules.DistinguishedMemberName(pi);
  619. if (!map.TryGetValue(dn, out mm)) {
  620. mm = new MappedDataMember(this, pi, mmap, ordinal);
  621. map.Add(InheritanceRules.DistinguishedMemberName(mm.Member), mm);
  622. dMembers.Add(mm);
  623. this.InitSpecialMember(mm);
  624. }
  625. ValidatePrimaryKeyMember(mm);
  626. ordinal++;
  627. }
  628. }
  629. }
  630. this.dataMembers = dMembers.AsReadOnly();
  631. this.dataMemberMap = map;
  632. // Finally, make sure that all types in the mapping file were consumed.
  633. foreach(string name in namesSeen) {
  634. names.Remove(name);
  635. }
  636. foreach(var orphan in names) {
  637. Type aboveRoot = inheritanceRoot.Type.BaseType;
  638. while (aboveRoot!=null) {
  639. foreach(MemberInfo mi in aboveRoot.GetMembers(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)) {
  640. if(String.Compare(mi.Name, orphan.Value.MemberName, StringComparison.Ordinal)==0) {
  641. throw Error.MappedMemberHadNoCorrespondingMemberInType(orphan.Value.MemberName, type.Name);
  642. }
  643. }
  644. aboveRoot = aboveRoot.BaseType;
  645. }
  646. }
  647. }
  648. }
  649. private void InitSpecialMember(MetaDataMember mm) {
  650. // Can only have one auto gen member that is also an identity member,
  651. // except if that member is a computed column (since they are implicitly auto gen)
  652. if (mm.IsDbGenerated && mm.IsPrimaryKey && string.IsNullOrEmpty(mm.Expression)) {
  653. if (this.dbGeneratedIdentity != null) {
  654. throw Error.TwoMembersMarkedAsPrimaryKeyAndDBGenerated(mm.Member, this.dbGeneratedIdentity.Member);
  655. }
  656. this.dbGeneratedIdentity = mm;
  657. }
  658. if (mm.IsPrimaryKey && !MappingSystem.IsSupportedIdentityType(mm.Type))
  659. {
  660. throw Error.IdentityClrTypeNotSupported(mm.DeclaringType, mm.Name, mm.Type);
  661. }
  662. if (mm.IsVersion) {
  663. if (this.version != null) {
  664. throw Error.TwoMembersMarkedAsRowVersion(mm.Member, this.version.Member);
  665. }
  666. this.version = mm;
  667. }
  668. if (mm.IsDiscriminator) {
  669. if (this.discriminator != null) {
  670. if (!InheritanceRules.AreSameMember(this.discriminator.Member, mm.Member)) {
  671. throw Error.TwoMembersMarkedAsInheritanceDiscriminator(mm.Member, this.discriminator.Member);
  672. }
  673. }
  674. else {
  675. this.discriminator = mm;
  676. }
  677. }
  678. }
  679. #endregion
  680. public override MetaModel Model {
  681. get { return this.model; }
  682. }
  683. public override MetaTable Table {
  684. get { return this.table; }
  685. }
  686. public override Type Type {
  687. get { return this.type; }
  688. }
  689. public override string Name {
  690. get { return this.type.Name; }
  691. }
  692. public override bool IsEntity {
  693. get {
  694. if (this.table != null) {
  695. return table.RowType.IdentityMembers.Count > 0;
  696. }
  697. return false;
  698. }
  699. }
  700. public override bool CanInstantiate {
  701. get { return !this.type.IsAbstract && (this == this.InheritanceRoot || this.HasInheritanceCode); }
  702. }
  703. public override MetaDataMember DBGeneratedIdentityMember {
  704. get { return this.dbGeneratedIdentity; }
  705. }
  706. public override MetaDataMember VersionMember {
  707. get { return this.version; }
  708. }
  709. public override MetaDataMember Discriminator {
  710. get { return this.discriminator; }
  711. }
  712. public override bool HasUpdateCheck {
  713. get {
  714. foreach (MetaDataMember member in this.PersistentDataMembers) {
  715. if (member.UpdateCheck != UpdateCheck.Never) {
  716. return true;
  717. }
  718. }
  719. return false;
  720. }
  721. }
  722. public override bool HasInheritance {
  723. get { return this.inheritanceRoot.HasInheritance; }
  724. }
  725. public override object InheritanceCode {
  726. get { return this.inheritanceCode; }
  727. }
  728. public override bool HasInheritanceCode {
  729. get { return this.InheritanceCode != null; }
  730. }
  731. public override bool IsInheritanceDefault {
  732. get { return this.InheritanceDefault == this; }
  733. }
  734. public override MetaType InheritanceDefault {
  735. get {
  736. if (this.inheritanceRoot == this)
  737. throw Error.CannotGetInheritanceDefaultFromNonInheritanceClass();
  738. return this.InheritanceRoot.InheritanceDefault;
  739. }
  740. }
  741. public override MetaType InheritanceRoot {
  742. get { return this.inheritanceRoot; }
  743. }
  744. public override MetaType InheritanceBase {
  745. get {
  746. // LOCKING: Cannot initialize at construction
  747. if (!this.inheritanceBaseSet && this.inheritanceBase == null) {
  748. lock (this.locktarget) {
  749. if (this.inheritanceBase == null) {
  750. this.inheritanceBase = InheritanceBaseFinder.FindBase(this);
  751. this.inheritanceBaseSet = true;
  752. }
  753. }
  754. }
  755. return this.inheritanceBase;
  756. }
  757. }
  758. public override ReadOnlyCollection<MetaType> InheritanceTypes {
  759. get { return this.inheritanceRoot.InheritanceTypes; }
  760. }
  761. public override ReadOnlyCollection<MetaType> DerivedTypes {
  762. get {
  763. // LOCKING: Cannot initialize at construction because derived types
  764. // won't exist yet.
  765. if (this.derivedTypes == null) {
  766. lock (this.locktarget) {
  767. if (this.derivedTypes == null) {
  768. List<MetaType> dTypes = new List<MetaType>();
  769. foreach (MetaType mt in this.InheritanceTypes) {
  770. if (mt.Type.BaseType == this.type)
  771. dTypes.Add(mt);
  772. }
  773. this.derivedTypes = dTypes.AsReadOnly();
  774. }
  775. }
  776. }
  777. return this.derivedTypes;
  778. }
  779. }
  780. public override MetaType GetInheritanceType(Type inheritanceType) {
  781. foreach (MetaType mt in this.InheritanceTypes)
  782. if (mt.Type == inheritanceType)
  783. return mt;
  784. return null;
  785. }
  786. public override MetaType GetTypeForInheritanceCode(object key) {
  787. if (this.InheritanceRoot.Discriminator.Type == typeof(string)) {
  788. string skey = (string)key;
  789. foreach (MetaType mt in this.InheritanceRoot.InheritanceTypes) {
  790. if (string.Compare((string)mt.InheritanceCode, skey, StringComparison.OrdinalIgnoreCase) == 0)
  791. return mt;
  792. }
  793. }
  794. else {
  795. foreach (MetaType mt in this.InheritanceRoot.InheritanceTypes) {
  796. if (object.Equals(mt.InheritanceCode, key))
  797. return mt;
  798. }
  799. }
  800. return null;
  801. }
  802. public override ReadOnlyCollection<MetaDataMember> DataMembers {
  803. get { return this.dataMembers; }
  804. }
  805. public override ReadOnlyCollection<MetaDataMember> PersistentDataMembers {
  806. get { return this.persistentDataMembers; }
  807. }
  808. public override ReadOnlyCollection<MetaDataMember> IdentityMembers {
  809. get { return this.identities; }
  810. }
  811. public override ReadOnlyCollection<MetaAssociation> Associations {
  812. get {
  813. // LOCKING: Associations are late-expanded so that cycles are broken.
  814. if (this.associations == null) {
  815. lock (this.locktarget) {
  816. if (this.associations == null) {
  817. this.associations = this.dataMembers.Where(m => m.IsAssociation).Select(m => m.Association).ToList().AsReadOnly();
  818. }
  819. }
  820. }
  821. return this.associations;
  822. }
  823. }
  824. public override MetaDataMember GetDataMember(MemberInfo mi) {
  825. if (mi == null)
  826. throw Error.ArgumentNull("mi");
  827. MetaDataMember mm;
  828. if (this.dataMemberMap.TryGetValue(InheritanceRules.DistinguishedMemberName(mi), out mm)) {
  829. return mm;
  830. } else {
  831. if (mi.DeclaringType.IsInterface) {
  832. throw Error.MappingOfInterfacesMemberIsNotSupported(mi.DeclaringType.Name, mi.Name);
  833. } else { //the member is not mapped in the base class
  834. throw Error.UnmappedClassMember(mi.DeclaringType.Name, mi.Name);
  835. }
  836. }
  837. }
  838. public override MethodInfo OnLoadedMethod {
  839. get {
  840. this.InitMethods();
  841. return this.onLoadedMethod;
  842. }
  843. }
  844. public override MethodInfo OnValidateMethod {
  845. get {
  846. this.InitMethods();
  847. return this.onValidateMethod;
  848. }
  849. }
  850. public override bool HasAnyValidateMethod {
  851. get {
  852. this.InitMethods();
  853. return this.hasAnyValidateMethod;
  854. }
  855. }
  856. public override bool HasAnyLoadMethod {
  857. get {
  858. this.InitMethods();
  859. return this.hasAnyLoadMethod;
  860. }
  861. }
  862. public override string ToString() {
  863. return this.Name;
  864. }
  865. }
  866. internal sealed class MappedDataMember : MetaDataMember {
  867. MetaType declaringType;
  868. MemberInfo member;
  869. MemberInfo storageMember;
  870. int ordinal;
  871. Type type;
  872. bool hasAccessors;
  873. MetaAccessor accPublic;
  874. MetaAccessor accPrivate;
  875. MetaAccessor accDefValue;
  876. MetaAccessor accDefSource;
  877. MemberMapping memberMap;
  878. MappedAssociation assoc;
  879. bool isNullableType;
  880. bool isDeferred;
  881. bool isPrimaryKey;
  882. bool isVersion;
  883. bool isDBGenerated;
  884. bool isDiscriminator;
  885. bool canBeNull = true;
  886. string dbType;
  887. string expression;
  888. string mappedName;
  889. UpdateCheck updateCheck = UpdateCheck.Never;
  890. AutoSync autoSync = AutoSync.Never;
  891. object locktarget = new object(); // Hold locks on private object rather than public MetaType.
  892. bool hasLoadMethod;
  893. MethodInfo loadMethod;
  894. internal MappedDataMember(MetaType declaringType, MemberInfo mi, MemberMapping map, int ordinal) {
  895. this.declaringType = declaringType;
  896. this.member = mi;
  897. this.ordinal = ordinal;
  898. this.type = TypeSystem.GetMemberType(mi);
  899. this.isNullableType = TypeSystem.IsNullableType(this.type);
  900. this.memberMap = map;
  901. if (this.memberMap != null && this.memberMap.StorageMemberName != null) {
  902. MemberInfo[] mis = mi.DeclaringType.GetMember(this.memberMap.StorageMemberName, BindingFlags.Instance | BindingFlags.NonPublic);
  903. if (mis == null || mis.Length != 1) {
  904. throw Error.BadStorageProperty(this.memberMap.StorageMemberName, mi.DeclaringType, mi.Name);
  905. }
  906. this.storageMember = mis[0];
  907. }
  908. Type storageType = this.storageMember != null ? TypeSystem.GetMemberType(this.storageMember) : this.type;
  909. this.isDeferred = IsDeferredType(storageType);
  910. ColumnMapping cmap = map as ColumnMapping;
  911. if (cmap != null && cmap.IsDbGenerated && cmap.IsPrimaryKey) {
  912. // auto-gen identities must be synced on insert
  913. if ((cmap.AutoSync != AutoSync.Default) && (cmap.AutoSync != AutoSync.OnInsert)) {
  914. throw Error.IncorrectAutoSyncSpecification(mi.Name);
  915. }
  916. }
  917. if (cmap != null) {
  918. this.isPrimaryKey = cmap.IsPrimaryKey;
  919. this.isVersion = cmap.IsVersion;
  920. this.isDBGenerated = cmap.IsDbGenerated || !string.IsNullOrEmpty(cmap.Expression) || this.isVersion;
  921. this.isDiscriminator = cmap.IsDiscriminator;
  922. this.canBeNull = cmap.CanBeNull == null ? this.isNullableType || !this.type.IsValueType : (bool)cmap.CanBeNull;
  923. this.dbType = cmap.DbType;
  924. this.expression = cmap.Expression;
  925. this.updateCheck = cmap.UpdateCheck;
  926. // auto-gen keys are always and only synced on insert
  927. if (this.IsDbGenerated && this.IsPrimaryKey) {
  928. this.autoSync = AutoSync.OnInsert;
  929. }
  930. else if (cmap.AutoSync != AutoSync.Default) {
  931. // if the user has explicitly set it, use their value
  932. this.autoSync = cmap.AutoSync;
  933. }
  934. else if (this.IsDbGenerated) {
  935. // database generated members default to always
  936. this.autoSync = AutoSync.Always;
  937. }
  938. }
  939. this.mappedName = this.memberMap.DbName != null ? this.memberMap.DbName : this.member.Name;
  940. }
  941. private void InitAccessors() {
  942. if (!this.hasAccessors) {
  943. lock (this.locktarget) {
  944. if (!this.hasAccessors) {
  945. if (this.storageMember != null) {
  946. this.accPrivate = MakeMemberAccessor(this.member.ReflectedType, this.storageMember, null);
  947. if (this.isDeferred) {
  948. MakeDeferredAccessors(this.member.ReflectedType, this.accPrivate, out this.accPrivate, out this.accDefValue, out this.accDefSource);
  949. }
  950. this.accPublic = MakeMemberAccessor(this.member.ReflectedType, this.member, this.accPrivate);
  951. }
  952. else {
  953. this.accPublic = this.accPrivate = MakeMemberAccessor(this.member.ReflectedType, this.member, null);
  954. if (this.isDeferred) {
  955. MakeDeferredAccessors(this.member.ReflectedType, this.accPrivate, out this.accPrivate, out this.accDefValue, out this.accDefSource);
  956. }
  957. }
  958. this.hasAccessors = true;
  959. }
  960. }
  961. }
  962. }
  963. public override MetaType DeclaringType {
  964. get { return this.declaringType; }
  965. }
  966. public override bool IsDeclaredBy(MetaType metaType) {
  967. if (metaType == null) {
  968. throw Error.ArgumentNull("metaType");
  969. }
  970. return metaType.Type == this.member.DeclaringType;
  971. }
  972. public override MemberInfo Member {
  973. get { return this.member; }
  974. }
  975. public override MemberInfo StorageMember {
  976. get { return this.storageMember; }
  977. }
  978. public override string Name {
  979. get { return this.member.Name; }
  980. }
  981. public override int Ordinal {
  982. get { return this.ordinal; }
  983. }
  984. public override Type Type {
  985. get { return this.type; }
  986. }
  987. public override MetaAccessor MemberAccessor {
  988. get {
  989. this.InitAccessors();
  990. return this.accPublic;
  991. }
  992. }
  993. public override MetaAccessor StorageAccessor {
  994. get {
  995. this.InitAccessors();
  996. return this.accPrivate;
  997. }
  998. }
  999. public override MetaAccessor DeferredValueAccessor {
  1000. get {
  1001. this.InitAccessors();
  1002. return this.accDefValue;
  1003. }
  1004. }
  1005. public override MetaAccessor DeferredSourceAccessor {
  1006. get {
  1007. this.InitAccessors();
  1008. return this.accDefSource;
  1009. }
  1010. }
  1011. public override bool IsDeferred {
  1012. get { return this.isDeferred; }
  1013. }
  1014. public override bool IsPersistent {
  1015. get { return this.memberMap != null; }
  1016. }
  1017. public override bool IsAssociation {
  1018. get { return this.memberMap is AssociationMapping; }
  1019. }
  1020. public override bool IsPrimaryKey {
  1021. get { return this.isPrimaryKey; }
  1022. }
  1023. /// <summary>
  1024. /// Returns true if the member is explicitly marked as auto gen, or if the
  1025. /// member is computed or generated by the database server.
  1026. /// </summary>
  1027. public override bool IsDbGenerated {
  1028. get { return this.isDBGenerated; }
  1029. }
  1030. public override bool IsVersion {
  1031. get { return this.isVersion; }
  1032. }
  1033. public override bool IsDiscriminator {
  1034. get { return this.isDiscriminator; }
  1035. }
  1036. public override bool CanBeNull {
  1037. get { return this.canBeNull; }
  1038. }
  1039. public override string DbType {
  1040. get { return this.dbType; }
  1041. }
  1042. public override string Expression {
  1043. get { return this.expression; }
  1044. }
  1045. public override string MappedName {
  1046. get { return this.mappedName; }
  1047. }
  1048. public override UpdateCheck UpdateCheck {
  1049. get { return this.updateCheck; }
  1050. }
  1051. public override AutoSync AutoSync {
  1052. get { return this.autoSync; }
  1053. }
  1054. public override MetaAssociation Association {
  1055. get {
  1056. if (this.IsAssociation) {
  1057. // LOCKING: This deferral isn't an optimization. It can't be done in the constructor
  1058. // because there may be loops in the association graph.
  1059. if (this.assoc == null) {
  1060. lock (this.locktarget) {
  1061. if (this.assoc == null) {
  1062. this.assoc = new MappedAssociation(this, (AssociationMapping)this.memberMap);
  1063. }
  1064. }
  1065. }
  1066. }
  1067. return this.assoc;
  1068. }
  1069. }
  1070. public override MethodInfo LoadMethod {
  1071. get {
  1072. if (this.hasLoadMethod == false && this.IsDeferred) {
  1073. // defer searching for this access method until we really need to know
  1074. this.loadMethod = MethodFinder.FindMethod(
  1075. ((MappedMetaModel)this.declaringType.Model).ContextType,
  1076. "Load" + this.member.Name,
  1077. BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic,
  1078. new Type[] { this.DeclaringType.Type }
  1079. );
  1080. this.hasLoadMethod = true;
  1081. }
  1082. return this.loadMethod;
  1083. }
  1084. }
  1085. private bool IsDeferredType(Type clrType) {
  1086. if (clrType == null || clrType == typeof(object)) {
  1087. return false;
  1088. }
  1089. if (clrType.IsGenericType) {
  1090. Type gtype = clrType.GetGenericTypeDefinition();
  1091. return gtype == typeof(Link<>) ||
  1092. typeof(EntitySet<>).IsAssignableFrom(gtype) ||
  1093. typeof(EntityRef<>).IsAssignableFrom(gtype) ||
  1094. IsDeferredType(clrType.BaseType);
  1095. }
  1096. return false;
  1097. }
  1098. private static MetaAccessor MakeMemberAccessor(Type accessorType, MemberInfo mi, MetaAccessor storage) {
  1099. FieldInfo fi = mi as FieldInfo;
  1100. MetaAccessor acc = null;
  1101. if (fi != null) {
  1102. acc = FieldAccessor.Create(accessorType, fi);
  1103. }
  1104. else {
  1105. PropertyInfo pi = (PropertyInfo)mi;
  1106. acc = PropertyAccessor.Create(accessorType, pi, storage);
  1107. }
  1108. return acc;
  1109. }
  1110. [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)]
  1111. private static void MakeDeferredAccessors(
  1112. Type declaringType, MetaAccessor accessor,
  1113. out MetaAccessor accessorValue, out MetaAccessor accessorDeferredValue, out MetaAccessor accessorDeferredSource
  1114. ) {
  1115. if (accessor.Type.IsGenericType) {
  1116. Type gtype = accessor.Type.GetGenericTypeDefinition();
  1117. Type itemType = accessor.Type.GetGenericArguments()[0];
  1118. if (gtype == typeof(Link<>)) {
  1119. accessorValue = CreateAccessor(typeof(LinkValueAccessor<,>).MakeGenericType(declaringType, itemType), accessor);
  1120. accessorDeferredValue = CreateAccessor(typeof(LinkDefValueAccessor<,>).MakeGenericType(declaringType, itemType), accessor);
  1121. accessorDeferredSource = CreateAccessor(typeof(LinkDefSourceAccessor<,>).MakeGenericType(declaringType, itemType), accessor);
  1122. return;
  1123. }
  1124. else if (typeof(EntityRef<>).IsAssignableFrom(gtype)) {
  1125. accessorValue = CreateAccessor(typeof(EntityRefValueAccessor<,>).MakeGenericType(declaringType, itemType), accessor);
  1126. accessorDeferredValue = CreateAccessor(typeof(EntityRefDefValueAccessor<,>).MakeGenericType(declaringType, itemType), accessor);
  1127. accessorDeferredSource = CreateAccessor(typeof(EntityRefDefSourceAccessor<,>).MakeGenericType(declaringType, itemType), accessor);
  1128. return;
  1129. }
  1130. else if (typeof(EntitySet<>).IsAssignableFrom(gtype)) {
  1131. accessorValue = CreateAccessor(typeof(EntitySetValueAccessor<,>).MakeGenericType(declaringType, itemType), accessor);
  1132. accessorDeferredValue = CreateAccessor(typeof(EntitySetDefValueAccessor<,>).MakeGenericType(declaringType, itemType), accessor);
  1133. accessorDeferredSource = CreateAccessor(typeof(EntitySetDefSourceAccessor<,>).MakeGenericType(declaringType, itemType), accessor);
  1134. return;
  1135. }
  1136. }
  1137. throw Error.UnhandledDeferredStorageType(accessor.Type);
  1138. }
  1139. private static MetaAccessor CreateAccessor(Type accessorType, params object[] args) {
  1140. return (MetaAccessor)Activator.CreateInstance(accessorType, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, args, null);
  1141. }
  1142. }
  1143. internal class MappedAssociation : MetaAssociationImpl {
  1144. MappedDataMember thisMember;
  1145. MetaDataMember otherMember;
  1146. MetaType otherType;
  1147. ReadOnlyCollection<MetaDataMember> thisKey;
  1148. ReadOnlyCollection<MetaDataMember> otherKey;
  1149. bool isMany;
  1150. bool isForeignKey;
  1151. bool isNullable;
  1152. bool thisKeyIsPrimaryKey;
  1153. bool otherKeyIsPrimaryKey;
  1154. AssociationMapping assocMap;
  1155. internal MappedAssociation(MappedDataMember mm, AssociationMapping assocMap) {
  1156. this.thisMember = mm;
  1157. this.assocMap = assocMap;
  1158. this.Init();
  1159. this.InitOther();
  1160. //validate the number of ThisKey columns is the same as the number of OtherKey columns
  1161. if (this.thisKey.Count != this.otherKey.Count && this.thisKey.Count > 0 && this.otherKey.Count > 0) {
  1162. throw Error.MismatchedThisKeyOtherKey(thisMember.Name, thisMember.DeclaringType.Name);
  1163. }
  1164. }
  1165. #region Initialization
  1166. private void Init() {
  1167. this.isMany = TypeSystem.IsSequenceType(this.thisMember.Type);
  1168. this.thisKey = (this.assocMap.ThisKey != null)
  1169. ? MakeKeys(this.thisMember.DeclaringType, this.assocMap.ThisKey)
  1170. : this.thisMember.DeclaringType.IdentityMembers;
  1171. // this association refers to the parent if thisKey is not our own identity
  1172. this.thisKeyIsPrimaryKey = AreEqual(this.thisKey, this.thisMember.DeclaringType.IdentityMembers);
  1173. this.isForeignKey = this.assocMap.IsForeignKey;
  1174. // if any key members are not nullable, the association is not nullable
  1175. this.isNullable = true;
  1176. foreach (MetaDataMember mm in this.thisKey) {
  1177. if (mm == null)
  1178. throw Error.UnexpectedNull("MetaDataMember");
  1179. if (!mm.CanBeNull) {
  1180. this.isNullable = false;
  1181. break;
  1182. }
  1183. }
  1184. // validate DeleteOnNull specification
  1185. if (assocMap.DeleteOnNull == true) {
  1186. if (!(isForeignKey && !isMany && !isNullable)) {
  1187. throw Error.InvalidDeleteOnNullSpecification(thisMember);
  1188. }
  1189. }
  1190. }
  1191. private void InitOther() {
  1192. if (this.otherType == null) {
  1193. Type ot = this.isMany ? TypeSystem.GetElementType(this.thisMember.Type) : this.thisMember.Type;
  1194. this.otherType = this.thisMember.DeclaringType.Model.GetMetaType(ot);
  1195. System.Diagnostics.Debug.Assert(this.otherType.IsEntity);
  1196. this.otherKey = (assocMap.OtherKey != null)
  1197. ? MakeKeys(this.otherType, this.assocMap.OtherKey)
  1198. : this.otherType.IdentityMembers;
  1199. this.otherKeyIsPrimaryKey = AreEqual(this.otherKey, this.otherType.IdentityMembers);
  1200. foreach (MetaDataMember omm in this.otherType.DataMembers) {
  1201. if (omm.IsAssociation && omm != this.thisMember && omm.MappedName == this.thisMember.MappedName) {
  1202. this.otherMember = omm;
  1203. break;
  1204. }
  1205. }
  1206. }
  1207. }
  1208. #endregion
  1209. public override MetaDataMember ThisMember {
  1210. get { return this.thisMember; }
  1211. }
  1212. public override ReadOnlyCollection<MetaDataMember> ThisKey {
  1213. get { return this.thisKey; }
  1214. }
  1215. public override MetaDataMember OtherMember {
  1216. get { return this.otherMember; }
  1217. }
  1218. public override ReadOnlyCollection<MetaDataMember> OtherKey {
  1219. get { return this.otherKey; }
  1220. }
  1221. public override MetaType OtherType {
  1222. get { return this.otherType; }
  1223. }
  1224. public override bool IsMany {
  1225. get { return this.isMany; }
  1226. }
  1227. public override bool IsForeignKey {
  1228. get { return this.isForeignKey; }
  1229. }
  1230. public override bool IsUnique {
  1231. get { return this.assocMap.IsUnique; }
  1232. }
  1233. public override bool IsNullable {
  1234. get { return this.isNullable; }
  1235. }
  1236. public override bool ThisKeyIsPrimaryKey {
  1237. get { return this.thisKeyIsPrimaryKey; }
  1238. }
  1239. public override bool OtherKeyIsPrimaryKey {
  1240. get { return this.otherKeyIsPrimaryKey; }
  1241. }
  1242. public override string DeleteRule {
  1243. get {
  1244. return this.assocMap.DeleteRule;
  1245. }
  1246. }
  1247. public override bool DeleteOnNull {
  1248. get {
  1249. return this.assocMap.DeleteOnNull;
  1250. }
  1251. }
  1252. }
  1253. class MappedFunction : MetaFunction {
  1254. MetaModel model;
  1255. FunctionMapping map;
  1256. MethodInfo method;
  1257. ReadOnlyCollection<MetaParameter> parameters;
  1258. MetaParameter returnParameter;
  1259. ReadOnlyCollection<MetaType> rowTypes;
  1260. static ReadOnlyCollection<MetaParameter> _emptyParameters = new List<MetaParameter>(0).AsReadOnly();
  1261. static ReadOnlyCollection<MetaType> _emptyTypes = new List<MetaType>(0).AsReadOnly();
  1262. [ResourceExposure(ResourceScope.Assembly | ResourceScope.Machine)] // map parameter contains type names.
  1263. [ResourceConsumption(ResourceScope.Assembly | ResourceScope.Machine)] // FindType method call.
  1264. internal MappedFunction(MappedMetaModel model, FunctionMapping map, MethodInfo method) {
  1265. this.model = model;
  1266. this.map = map;
  1267. this.method = method;
  1268. this.rowTypes = _emptyTypes;
  1269. if (map.Types.Count == 0 && this.method.ReturnType == typeof(IMultipleResults)) {
  1270. throw Error.NoResultTypesDeclaredForFunction(method.Name);
  1271. }
  1272. else if (map.Types.Count > 1 && this.method.ReturnType != typeof(IMultipleResults)) {
  1273. throw Error.TooManyResultTypesDeclaredForFunction(method.Name);
  1274. }
  1275. else if (map.Types.Count == 1 && this.method.ReturnType != typeof(IMultipleResults)) {
  1276. Type elementType = TypeSystem.GetElementType(method.ReturnType);
  1277. this.rowTypes = new List<MetaType>(1) { this.GetMetaType(map.Types[0], elementType) }.AsReadOnly();
  1278. }
  1279. else if (map.Types.Count > 0) {
  1280. List<MetaType> rowTypes = new List<MetaType>();
  1281. foreach (TypeMapping rtm in map.Types) {
  1282. Type elementType = model.FindType(rtm.Name);
  1283. if (elementType == null) {
  1284. throw Error.CouldNotFindElementTypeInModel(rtm.Name);
  1285. }
  1286. MetaType mt = this.GetMetaType(rtm, elementType);
  1287. // Only add unique meta types
  1288. if (!rowTypes.Contains(mt)) {
  1289. rowTypes.Add(mt);
  1290. }
  1291. }
  1292. this.rowTypes = rowTypes.AsReadOnly();
  1293. }
  1294. else if (map.FunReturn != null) {
  1295. this.returnParameter = new MappedReturnParameter(method.ReturnParameter, map.FunReturn);
  1296. }
  1297. // Parameters.
  1298. ParameterInfo[] pis = this.method.GetParameters();
  1299. if (pis.Length > 0) {
  1300. List<MetaParameter> mps = new List<MetaParameter>(pis.Length);
  1301. if (this.map.Parameters.Count != pis.Length) {
  1302. throw Error.IncorrectNumberOfParametersMappedForMethod(this.map.MethodName);
  1303. }
  1304. for (int i = 0; i < pis.Length; i++) {
  1305. mps.Add(new MappedParameter(pis[i], this.map.Parameters[i]));
  1306. }
  1307. this.parameters = mps.AsReadOnly();
  1308. }
  1309. else {
  1310. this.parameters = _emptyParameters;
  1311. }
  1312. }
  1313. /// <summary>
  1314. /// For the specified type, if it is a mapped type, use the Table
  1315. /// metatype to get the correct inheritance metatype,
  1316. /// otherwise create a new meta type.
  1317. [ResourceExposure(ResourceScope.Assembly | ResourceScope.Machine)] // Parameter contains various type references.
  1318. [ResourceConsumption(ResourceScope.Assembly | ResourceScope.Machine)] // MappedRootType constructor call.
  1319. private MetaType GetMetaType(TypeMapping tm, Type elementType) {
  1320. MetaTable tbl = model.GetTable(elementType);
  1321. if (tbl != null) {
  1322. return tbl.RowType.GetInheritanceType(elementType);
  1323. }
  1324. return new MappedRootType((MappedMetaModel)model, null, tm, elementType);
  1325. }
  1326. public override ReadOnlyCollection<MetaParameter> Parameters {
  1327. get { return this.parameters; }
  1328. }
  1329. public override string MappedName {
  1330. get { return this.map.Name; }
  1331. }
  1332. public override MethodInfo Method {
  1333. get { return this.method; }
  1334. }
  1335. public override MetaModel Model {
  1336. get { return this.model; }
  1337. }
  1338. public override string Name {
  1339. get { return this.method.Name; }
  1340. }
  1341. public override bool IsComposable {
  1342. get { return this.map.IsComposable; }
  1343. }
  1344. public override MetaParameter ReturnParameter {
  1345. get { return this.returnParameter; }
  1346. }
  1347. public override bool HasMultipleResults {
  1348. get { return this.method.ReturnType == typeof(IMultipleResults); }
  1349. }
  1350. public override ReadOnlyCollection<MetaType> ResultRowTypes {
  1351. get { return this.rowTypes; }
  1352. }
  1353. }
  1354. internal sealed class MappedParameter : MetaParameter {
  1355. private ParameterInfo parameterInfo;
  1356. private ParameterMapping map;
  1357. public MappedParameter(ParameterInfo parameterInfo, ParameterMapping map) {
  1358. this.parameterInfo = parameterInfo;
  1359. this.map = map;
  1360. }
  1361. public override ParameterInfo Parameter {
  1362. get { return this.parameterInfo; }
  1363. }
  1364. public override string Name {
  1365. get { return this.parameterInfo.Name; }
  1366. }
  1367. public override string MappedName {
  1368. get { return this.map.Name; }
  1369. }
  1370. public override Type ParameterType {
  1371. get { return this.parameterInfo.ParameterType; }
  1372. }
  1373. public override string DbType {
  1374. get { return this.map.DbType; }
  1375. }
  1376. }
  1377. internal sealed class MappedReturnParameter : MetaParameter {
  1378. private ParameterInfo parameterInfo;
  1379. private ReturnMapping map;
  1380. public MappedReturnParameter(ParameterInfo parameterInfo, ReturnMapping map) {
  1381. this.parameterInfo = parameterInfo;
  1382. this.map = map;
  1383. }
  1384. public override ParameterInfo Parameter {
  1385. get { return this.parameterInfo; }
  1386. }
  1387. public override string Name {
  1388. get { return null; }
  1389. }
  1390. public override string MappedName {
  1391. get { return null; }
  1392. }
  1393. public override Type ParameterType {
  1394. get { return this.parameterInfo.ParameterType; }
  1395. }
  1396. public override string DbType {
  1397. get { return this.map.DbType; }
  1398. }
  1399. }
  1400. internal abstract class MetaAssociationImpl : MetaAssociation {
  1401. private static char[] keySeparators = new char[] { ',' };
  1402. /// <summary>
  1403. /// Given a MetaType and a set of key fields, return the set of MetaDataMembers
  1404. /// corresponding to the key.
  1405. /// </summary>
  1406. protected static ReadOnlyCollection<MetaDataMember> MakeKeys(MetaType mtype, string keyFields) {
  1407. string[] names = keyFields.Split(keySeparators);
  1408. MetaDataMember[] members = new MetaDataMember[names.Length];
  1409. for (int i = 0; i < names.Length; i++) {
  1410. names[i] = names[i].Trim();
  1411. MemberInfo[] rmis = mtype.Type.GetMember(names[i], BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
  1412. if (rmis == null || rmis.Length != 1) {
  1413. throw Error.BadKeyMember(names[i], keyFields, mtype.Name);
  1414. }
  1415. members[i] = mtype.GetDataMember(rmis[0]);
  1416. if (members[i] == null) {
  1417. throw Error.BadKeyMember(names[i], keyFields, mtype.Name);
  1418. }
  1419. }
  1420. return new List<MetaDataMember>(members).AsReadOnly();
  1421. }
  1422. /// <summary>
  1423. /// Compare two sets of keys for equality.
  1424. /// </summary>
  1425. protected static bool AreEqual(IEnumerable<MetaDataMember> key1, IEnumerable<MetaDataMember> key2) {
  1426. using (IEnumerator<MetaDataMember> e1 = key1.GetEnumerator()) {
  1427. using (IEnumerator<MetaDataMember> e2 = key2.GetEnumerator()) {
  1428. bool m1, m2;
  1429. for (m1 = e1.MoveNext(), m2 = e2.MoveNext(); m1 && m2; m1 = e1.MoveNext(), m2 = e2.MoveNext()) {
  1430. if (e1.Current != e2.Current)
  1431. return false;
  1432. }
  1433. if (m1 != m2)
  1434. return false;
  1435. }
  1436. }
  1437. return true;
  1438. }
  1439. public override string ToString() {
  1440. return string.Format(Globalization.CultureInfo.InvariantCulture, "{0} ->{1} {2}", ThisMember.DeclaringType.Name, IsMany ? "*" : "", OtherType.Name);
  1441. }
  1442. }
  1443. internal sealed class UnmappedType : MetaType {
  1444. MetaModel model;
  1445. Type type;
  1446. Dictionary<object, MetaDataMember> dataMemberMap;
  1447. ReadOnlyCollection<MetaDataMember> dataMembers;
  1448. ReadOnlyCollection<MetaType> inheritanceTypes;
  1449. object locktarget = new object(); // Hold locks on private object rather than public MetaType.
  1450. private static ReadOnlyCollection<MetaType> _emptyTypes = new List<MetaType>().AsReadOnly();
  1451. private static ReadOnlyCollection<MetaDataMember> _emptyDataMembers = new List<MetaDataMember>().AsReadOnly();
  1452. private static ReadOnlyCollection<MetaAssociation> _emptyAssociations = new List<MetaAssociation>().AsReadOnly();
  1453. internal UnmappedType(MetaModel model, Type type) {
  1454. this.model = model;
  1455. this.type = type;
  1456. }
  1457. public override MetaModel Model {
  1458. get { return this.model; }
  1459. }
  1460. public override MetaTable Table {
  1461. get { return null; }
  1462. }
  1463. public override Type Type {
  1464. get { return this.type; }
  1465. }
  1466. public override string Name {
  1467. get { return this.type.Name; }
  1468. }
  1469. public override bool IsEntity {
  1470. get { return false; }
  1471. }
  1472. public override bool CanInstantiate {
  1473. get { return !this.type.IsAbstract; }
  1474. }
  1475. public override MetaDataMember DBGeneratedIdentityMember {
  1476. get { return null; }
  1477. }
  1478. public override MetaDataMember VersionMember {
  1479. get { return null; }
  1480. }
  1481. public override MetaDataMember Discriminator {
  1482. get { return null; }
  1483. }
  1484. public override bool HasUpdateCheck {
  1485. get { return false; }
  1486. }
  1487. public override ReadOnlyCollection<MetaType> InheritanceTypes {
  1488. get {
  1489. if (this.inheritanceTypes == null) {
  1490. lock (this.locktarget) {
  1491. if (this.inheritanceTypes == null) {
  1492. this.inheritanceTypes = new MetaType[] { this }.ToList().AsReadOnly();
  1493. }
  1494. }
  1495. }
  1496. return this.inheritanceTypes;
  1497. }
  1498. }
  1499. public override MetaType GetInheritanceType(Type inheritanceType) {
  1500. if (inheritanceType == this.type)
  1501. return this;
  1502. return null;
  1503. }
  1504. public override ReadOnlyCollection<MetaType> DerivedTypes {
  1505. get { return _emptyTypes; }
  1506. }
  1507. public override MetaType GetTypeForInheritanceCode(object key) {
  1508. return null;
  1509. }
  1510. public override bool HasInheritance {
  1511. get { return false; }
  1512. }
  1513. public override bool HasInheritanceCode {
  1514. get { return false; }
  1515. }
  1516. public override object InheritanceCode {
  1517. get { return null; }
  1518. }
  1519. public override MetaType InheritanceRoot {
  1520. get { return this; }
  1521. }
  1522. public override MetaType InheritanceBase {
  1523. get { return null; }
  1524. }
  1525. public override MetaType InheritanceDefault {
  1526. get { return null; }
  1527. }
  1528. public override bool IsInheritanceDefault {
  1529. get { return false; }
  1530. }
  1531. public override ReadOnlyCollection<MetaDataMember> DataMembers {
  1532. get {
  1533. this.InitDataMembers();
  1534. return this.dataMembers;
  1535. }
  1536. }
  1537. public override ReadOnlyCollection<MetaDataMember> PersistentDataMembers {
  1538. get { return _emptyDataMembers; }
  1539. }
  1540. public override ReadOnlyCollection<MetaDataMember> IdentityMembers {
  1541. get {
  1542. this.InitDataMembers();
  1543. return this.dataMembers;
  1544. }
  1545. }
  1546. public override ReadOnlyCollection<MetaAssociation> Associations {
  1547. get { return _emptyAssociations; }
  1548. }
  1549. public override MetaDataMember GetDataMember(MemberInfo mi) {
  1550. if (mi == null)
  1551. throw Error.ArgumentNull("mi");
  1552. this.InitDataMembers();
  1553. if (this.dataMemberMap == null) {
  1554. lock (this.locktarget) {
  1555. if (this.dataMemberMap == null) {
  1556. Dictionary<object, MetaDataMember> map = new Dictionary<object, MetaDataMember>();
  1557. foreach (MetaDataMember mm in this.dataMembers) {
  1558. map.Add(InheritanceRules.DistinguishedMemberName(mm.Member), mm);
  1559. }
  1560. this.dataMemberMap = map;
  1561. }
  1562. }
  1563. }
  1564. object dn = InheritanceRules.DistinguishedMemberName(mi);
  1565. MetaDataMember mdm;
  1566. this.dataMemberMap.TryGetValue(dn, out mdm);
  1567. return mdm;
  1568. }
  1569. private void InitDataMembers() {
  1570. if (this.dataMembers == null) {
  1571. lock (this.locktarget) {
  1572. if (this.dataMembers == null) {
  1573. List<MetaDataMember> dMembers = new List<MetaDataMember>();
  1574. int ordinal = 0;
  1575. BindingFlags flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy;
  1576. foreach (FieldInfo fi in this.type.GetFields(flags)) {
  1577. MetaDataMember mm = new UnmappedDataMember(this, fi, ordinal);
  1578. dMembers.Add(mm);
  1579. ordinal++;
  1580. }
  1581. foreach (PropertyInfo pi in this.type.GetProperties(flags)) {
  1582. MetaDataMember mm = new UnmappedDataMember(this, pi, ordinal);
  1583. dMembers.Add(mm);
  1584. ordinal++;
  1585. }
  1586. this.dataMembers = dMembers.AsReadOnly();
  1587. }
  1588. }
  1589. }
  1590. }
  1591. public override string ToString() {
  1592. return this.Name;
  1593. }
  1594. public override MethodInfo OnLoadedMethod {
  1595. get { return null; }
  1596. }
  1597. public override MethodInfo OnValidateMethod {
  1598. get { return null; }
  1599. }
  1600. public override bool HasAnyValidateMethod {
  1601. get {
  1602. return false;
  1603. }
  1604. }
  1605. public override bool HasAnyLoadMethod {
  1606. get {
  1607. return false;
  1608. }
  1609. }
  1610. }
  1611. internal sealed class UnmappedDataMember : MetaDataMember {
  1612. MetaType declaringType;
  1613. MemberInfo member;
  1614. int ordinal;
  1615. Type type;
  1616. MetaAccessor accPublic;
  1617. object lockTarget = new object();
  1618. internal UnmappedDataMember(MetaType declaringType, MemberInfo mi, int ordinal) {
  1619. this.declaringType = declaringType;
  1620. this.member = mi;
  1621. this.ordinal = ordinal;
  1622. this.type = TypeSystem.GetMemberType(mi);
  1623. }
  1624. private void InitAccessors() {
  1625. if (this.accPublic == null) {
  1626. lock (this.lockTarget) {
  1627. if (this.accPublic == null) {
  1628. this.accPublic = MakeMemberAccessor(this.member.ReflectedType, this.member);
  1629. }
  1630. }
  1631. }
  1632. }
  1633. public override MetaType DeclaringType {
  1634. get { return this.declaringType; }
  1635. }
  1636. public override bool IsDeclaredBy(MetaType metaType) {
  1637. if (metaType == null) {
  1638. throw Error.ArgumentNull("metaType");
  1639. }
  1640. return metaType.Type == this.member.DeclaringType;
  1641. }
  1642. public override MemberInfo Member {
  1643. get { return this.member; }
  1644. }
  1645. public override MemberInfo StorageMember {
  1646. get { return this.member; }
  1647. }
  1648. public override string Name {
  1649. get { return this.member.Name; }
  1650. }
  1651. public override int Ordinal {
  1652. get { return this.ordinal; }
  1653. }
  1654. public override Type Type {
  1655. get { return this.type; }
  1656. }
  1657. public override MetaAccessor MemberAccessor {
  1658. get {
  1659. this.InitAccessors();
  1660. return this.accPublic;
  1661. }
  1662. }
  1663. public override MetaAccessor StorageAccessor {
  1664. get {
  1665. this.InitAccessors();
  1666. return this.accPublic;
  1667. }
  1668. }
  1669. public override MetaAccessor DeferredValueAccessor {
  1670. get { return null; }
  1671. }
  1672. public override MetaAccessor DeferredSourceAccessor {
  1673. get { return null; }
  1674. }
  1675. public override bool IsDeferred {
  1676. get { return false; }
  1677. }
  1678. public override bool IsPersistent {
  1679. get { return false; }
  1680. }
  1681. public override bool IsAssociation {
  1682. get { return false; }
  1683. }
  1684. public override bool IsPrimaryKey {
  1685. get { return false; }
  1686. }
  1687. public override bool IsDbGenerated {
  1688. get { return false; }
  1689. }
  1690. public override bool IsVersion {
  1691. get { return false; }
  1692. }
  1693. public override bool IsDiscriminator {
  1694. get { return false; }
  1695. }
  1696. public override bool CanBeNull {
  1697. get { return !this.type.IsValueType || TypeSystem.IsNullableType(this.type); }
  1698. }
  1699. public override string DbType {
  1700. get { return null; }
  1701. }
  1702. public override string Expression {
  1703. get { return null; }
  1704. }
  1705. public override string MappedName {
  1706. get { return this.member.Name; }
  1707. }
  1708. public override UpdateCheck UpdateCheck {
  1709. get { return UpdateCheck.Never; }
  1710. }
  1711. public override AutoSync AutoSync {
  1712. get { return AutoSync.Never; }
  1713. }
  1714. public override MetaAssociation Association {
  1715. get { return null; }
  1716. }
  1717. public override MethodInfo LoadMethod {
  1718. get { return null; }
  1719. }
  1720. private static MetaAccessor MakeMemberAccessor(Type accessorType, MemberInfo mi) {
  1721. FieldInfo fi = mi as FieldInfo;
  1722. MetaAccessor acc = null;
  1723. if (fi != null) {
  1724. acc = FieldAccessor.Create(accessorType, fi);
  1725. }
  1726. else {
  1727. PropertyInfo pi = (PropertyInfo)mi;
  1728. acc = PropertyAccessor.Create(accessorType, pi, null);
  1729. }
  1730. return acc;
  1731. }
  1732. }
  1733. }