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 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453
|
//---------------------------------------------------------------------
// <copyright file="StorageMappingItemLoader.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//
// @owner Microsoft
// @backupOwner Microsoft
//---------------------------------------------------------------------
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data.Common.Utils;
using System.Data.Metadata.Edm;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Schema;
using System.Xml.XPath;
using System.Data.Entity;
namespace System.Data.Mapping
{
using Triple = Pair<EntitySetBase, Pair<EntityTypeBase, bool>>;
/// <summary>
/// The class loads an MSL file into memory and exposes CSMappingMetadata interfaces.
/// The primary consumers of the interfaces are view genration and tools.
/// </summary>
/// <example>
/// For Example if conceptually you could represent the CS MSL file as following
/// --Mapping
/// --EntityContainerMapping ( CNorthwind-->SNorthwind )
/// --EntitySetMapping
/// --EntityTypeMapping
/// --TableMappingFragment
/// --EntityKey
/// --ScalarPropertyMap ( CMemberMetadata-->SMemberMetadata )
/// --ScalarPropertyMap ( CMemberMetadata-->SMemberMetadata )
/// --DiscriminatorProperyMap ( constant value-->SMemberMetadata )
/// --EntityTypeMapping
/// --TableMappingFragment
/// --EntityKey
/// --ScalarPropertyMap ( CMemberMetadata-->SMemberMetadata )
/// --ComplexPropertyMap
/// --ComplexTypeMap
/// --ScalarPropertyMap ( CMemberMetadata-->SMemberMetadata )
/// --ScalarProperyMap ( CMemberMetadata-->SMemberMetadata )
/// --DiscriminatorProperyMap ( constant value-->SMemberMetadata )
/// --AssociationSetMapping
/// --AssociationTypeMapping
/// --TableMappingFragment
/// --EndPropertyMap
/// --ScalarPropertyMap ( CMemberMetadata-->SMemberMetadata )
/// --ScalarProperyMap ( CMemberMetadata-->SMemberMetadata )
/// --EndPropertyMap
/// --ScalarPropertyMap ( CMemberMetadata-->SMemberMetadata )
/// --EntityContainerMapping ( CMyDatabase-->SMyDatabase )
/// --CompositionSetMapping
/// --CompositionTypeMapping
/// --TableMappingFragment
/// --ParentEntityKey
/// --ScalarPropertyMap ( CMemberMetadata-->SMemberMetadata )
/// --ScalarPropertyMap ( CMemberMetadata-->SMemberMetadata )
/// --EntityKey
/// --ScalarPropertyMap ( CMemberMetadata-->SMemberMetadata )
/// --ScalarPropertyMap ( CMemberMetadata-->Constant value )
/// --ComplexPropertyMap
/// --ComplexTypeMap
/// --ScalarPropertyMap ( CMemberMetadata-->SMemberMetadata )
/// --DiscriminatorProperyMap ( constant value-->SMemberMetadata )
/// --ScalarPropertyMap ( CMemberMetadata-->Constant value )
/// The CCMappingSchemaLoader loads an Xml file that has a conceptual structure
/// equivalent to the above example into in-memory data structure in a
/// top-dwon approach.
/// </example>
/// <remarks>
/// The loader uses XPathNavigator to parse the XML. The advantage of using XPathNavigator
/// over DOM is that it exposes the line number of the current xml content.
/// This is really helpful when throwing exceptions. Another advantage is
/// </remarks>
internal class StorageMappingItemLoader
{
#region Constructors
/// <summary>
/// Public constructor.
/// For Beta2 we wont support delay loading Mapping information and we would also support
/// only one mapping file for workspace.
/// </summary>
/// <param name="edmCollection"></param>
/// <param name="storeItemCollection"></param>
/// <param name="fileName"></param>
/// <param name="scalarMemberMappings">Dictionary to keep the list of all scalar member mappings</param>
internal StorageMappingItemLoader(XmlReader reader, StorageMappingItemCollection storageMappingItemCollection, string fileName, Dictionary<EdmMember, KeyValuePair<TypeUsage, TypeUsage>> scalarMemberMappings)
{
Debug.Assert(storageMappingItemCollection != null);
Debug.Assert(scalarMemberMappings != null);
this.m_storageMappingItemCollection = storageMappingItemCollection;
this.m_alias = new Dictionary<string, string>(StringComparer.Ordinal);
//The fileName field in this class will always have absolute path since
//StorageMappingItemCollection would have already done it while
//preparing the filePaths
if (fileName != null)
{
this.m_sourceLocation = fileName;
}
else
{
this.m_sourceLocation = null;
}
m_parsingErrors = new List<EdmSchemaError>();
this.m_scalarMemberMappings = scalarMemberMappings;
m_containerMapping = LoadMappingItems(reader);
if (m_currentNamespaceUri != null)
{
if (m_currentNamespaceUri == StorageMslConstructs.NamespaceUriV1)
{
m_version = StorageMslConstructs.MappingVersionV1;
}
else if (m_currentNamespaceUri == StorageMslConstructs.NamespaceUriV2)
{
m_version = StorageMslConstructs.MappingVersionV2;
}
else
{
Debug.Assert(m_currentNamespaceUri == StorageMslConstructs.NamespaceUriV3, "Did you add a new Namespace?");
m_version = StorageMslConstructs.MappingVersionV3;
}
}
}
#endregion
#region Fields
private Dictionary<string, string> m_alias; //To support the aliasing mechanism provided by MSL.
private StorageMappingItemCollection m_storageMappingItemCollection; //StorageMappingItemCollection
private string m_sourceLocation; //location identifier for the MSL file.
private List<EdmSchemaError> m_parsingErrors;
private Dictionary<EdmMember, KeyValuePair<TypeUsage, TypeUsage>> m_scalarMemberMappings; // dictionary of all the scalar member mappings - this is to validate that no property is mapped to different store types across mappings.
private bool m_hasQueryViews; //set to true if any of the SetMaps have a query view so that
private string m_currentNamespaceUri;
private StorageEntityContainerMapping m_containerMapping;
private double m_version;
// cached xsd schema
private static XmlSchemaSet s_mappingXmlSchema;
#endregion
#region Properties
internal double MappingVersion
{
get { return m_version; }
}
internal IList<EdmSchemaError> ParsingErrors
{
get { return m_parsingErrors; }
}
internal bool HasQueryViews
{
get { return m_hasQueryViews; }
}
internal StorageEntityContainerMapping ContainerMapping
{
get { return m_containerMapping; }
}
private EdmItemCollection EdmItemCollection
{
get { return m_storageMappingItemCollection.EdmItemCollection; }
}
private StoreItemCollection StoreItemCollection
{
get { return m_storageMappingItemCollection.StoreItemCollection; }
}
#endregion
#region Methods
/// <summary>
/// The LoadMappingSchema method loads the mapping file and initializes the
/// MappingSchema that represents this mapping file.
/// For Beta2 atleast, we will support only one EntityContainerMapping per mapping file.
/// </summary>
/// <returns></returns>
private StorageEntityContainerMapping LoadMappingItems(XmlReader innerReader)
{
// Using XPathDocument to load the xml file into memory.
XmlReader reader = GetSchemaValidatingReader(innerReader);
try
{
XPathDocument doc = new XPathDocument(reader);
// If there were any xsd validation errors, we would have caught these while creatring xpath document.
if (m_parsingErrors.Count != 0)
{
// If the errors were only warnings continue, otherwise return the errors without loading the mapping.
if (!MetadataHelper.CheckIfAllErrorsAreWarnings(m_parsingErrors))
{
return null;
}
}
// Create an XPathNavigator to navigate the document in a forward only manner.
// The XPathNavigator can also be used to run quries through the document while still maintaining
// the current position. This will be helpful in running validation rules that are not part of Schema.
XPathNavigator nav = doc.CreateNavigator();
return LoadMappingItems(nav.Clone());
}
catch (XmlException xmlException)
{
// There must have been a xml parsing exception. Add the exception information to the error list.
EdmSchemaError error = new EdmSchemaError(Strings.Mapping_InvalidMappingSchema_Parsing(xmlException.Message)
, (int)StorageMappingErrorCode.XmlSchemaParsingError, EdmSchemaErrorSeverity.Error, m_sourceLocation, xmlException.LineNumber, xmlException.LinePosition);
m_parsingErrors.Add(error);
}
// Do not close the wrapping reader here, as doing so will close the inner reader. See SQLBUDT 522950 for details.
return null;
}
private StorageEntityContainerMapping LoadMappingItems(XPathNavigator nav)
{
// XSD validation is not validating missing Root element.
if (!MoveToRootElement(nav) || (nav.NodeType != XPathNodeType.Element))
{
StorageMappingItemLoader.AddToSchemaErrors(
Strings.Mapping_Invalid_CSRootElementMissing(
StorageMslConstructs.NamespaceUriV1,
StorageMslConstructs.NamespaceUriV2,
StorageMslConstructs.NamespaceUriV3),
StorageMappingErrorCode.RootMappingElementMissing,
m_sourceLocation,
(IXmlLineInfo)nav, m_parsingErrors);
// There is no point in going forward if the required root element is not found.
return null;
}
StorageEntityContainerMapping entityContainerMap = LoadMappingChildNodes(nav.Clone());
// If there were any parsing errors, invalidate the entity container map and return null.
if (m_parsingErrors.Count != 0)
{
// If all the schema errors are warnings, don't return null.
if (!MetadataHelper.CheckIfAllErrorsAreWarnings(m_parsingErrors))
{
entityContainerMap = null;
}
}
return entityContainerMap;
}
private bool MoveToRootElement(XPathNavigator nav)
{
if (nav.MoveToChild(StorageMslConstructs.MappingElement, StorageMslConstructs.NamespaceUriV3))
{
// found v3 schema
m_currentNamespaceUri = StorageMslConstructs.NamespaceUriV3;
return true;
}
else if (nav.MoveToChild(StorageMslConstructs.MappingElement, StorageMslConstructs.NamespaceUriV2))
{
// found v2 schema
m_currentNamespaceUri = StorageMslConstructs.NamespaceUriV2;
return true;
}
else if (nav.MoveToChild(StorageMslConstructs.MappingElement, StorageMslConstructs.NamespaceUriV1))
{
m_currentNamespaceUri = StorageMslConstructs.NamespaceUriV1;
return true;
}
//the xml namespace corresponds to neither v1 namespace nor v2 namespace
return false;
}
/// <summary>
/// The method loads the child nodes for the root Mapping node
/// into the internal datastructures.
/// </summary>
private StorageEntityContainerMapping LoadMappingChildNodes(XPathNavigator nav)
{
bool hasContainerMapping;
// If there are any Alias elements in the document, they should be the first ones.
// This method can only move to the Alias element since comments, PIS etc wont have any Namespace
// though they could have same name as Alias element.
if (nav.MoveToChild(StorageMslConstructs.AliasElement, m_currentNamespaceUri))
{
// Collect all the alias elements.
do
{
m_alias.Add(StorageMappingItemLoader.GetAttributeValue(nav.Clone(), StorageMslConstructs.AliasKeyAttribute), StorageMappingItemLoader.GetAttributeValue(nav.Clone(), StorageMslConstructs.AliasValueAttribute));
} while (nav.MoveToNext(StorageMslConstructs.AliasElement, m_currentNamespaceUri));
// Now move on to the Next element that will be "EntityContainer" element.
hasContainerMapping = nav.MoveToNext(XPathNodeType.Element);
}
else
{
// Since there was no Alias element, move on to the Container element.
hasContainerMapping = nav.MoveToChild(XPathNodeType.Element);
}
// Load entity container mapping if any.
var containerMapping = hasContainerMapping ? LoadEntityContainerMapping(nav.Clone()) : null;
return containerMapping;
}
/// <summary>
/// The method loads and returns the EntityContainer Mapping node.
/// </summary>
private StorageEntityContainerMapping LoadEntityContainerMapping(XPathNavigator nav)
{
IXmlLineInfo navLineInfo = (IXmlLineInfo)nav;
// The element name can only be EntityContainerMapping element name since XSD validation should have guarneteed this.
Debug.Assert(nav.LocalName == StorageMslConstructs.EntityContainerMappingElement);
string entityContainerName = GetAttributeValue(nav.Clone(), StorageMslConstructs.CdmEntityContainerAttribute);
string storageEntityContainerName = GetAttributeValue(nav.Clone(), StorageMslConstructs.StorageEntityContainerAttribute);
bool generateUpdateViews = GetBoolAttributeValue(nav.Clone(), StorageMslConstructs.GenerateUpdateViews, true /* default is true */);
StorageEntityContainerMapping entityContainerMapping;
EntityContainer entityContainerType;
EntityContainer storageEntityContainerType;
// Now that we support partial mapping, we should first check if the entity container mapping is
// already present. If its already present, we should add the new child nodes to the existing entity container mapping
if (m_storageMappingItemCollection.TryGetItem<StorageEntityContainerMapping>(
entityContainerName, out entityContainerMapping))
{
entityContainerType = entityContainerMapping.EdmEntityContainer;
storageEntityContainerType = entityContainerMapping.StorageEntityContainer;
// The only thing we need to make sure is that the storage entity container mapping is the same.
if (storageEntityContainerName != storageEntityContainerType.Name)
{
AddToSchemaErrors(Strings.StorageEntityContainerNameMismatchWhileSpecifyingPartialMapping(
storageEntityContainerName, storageEntityContainerType.Name, entityContainerType.Name),
StorageMappingErrorCode.StorageEntityContainerNameMismatchWhileSpecifyingPartialMapping,
m_sourceLocation, navLineInfo, m_parsingErrors);
return null;
}
}
else
{
// At this point we know that the EdmEntityContainer has not been mapped already.
// If we do find that StorageEntityContainer has already been mapped, return null.
if (m_storageMappingItemCollection.ContainsStorageEntityContainer(storageEntityContainerName))
{
AddToSchemaErrorsWithMemberInfo(Strings.Mapping_AlreadyMapped_StorageEntityContainer, storageEntityContainerName,
StorageMappingErrorCode.AlreadyMappedStorageEntityContainer, m_sourceLocation, navLineInfo, m_parsingErrors);
return null;
}
// Get the CDM EntityContainer by this name from the metadata workspace.
this.EdmItemCollection.TryGetEntityContainer(entityContainerName, out entityContainerType);
if (entityContainerType == null)
{
AddToSchemaErrorsWithMemberInfo(Strings.Mapping_InvalidContent_EntityContainer,
entityContainerName, StorageMappingErrorCode.InvalidEntityContainer, m_sourceLocation,
navLineInfo, m_parsingErrors);
}
this.StoreItemCollection.TryGetEntityContainer(storageEntityContainerName, out storageEntityContainerType);
if (storageEntityContainerType == null)
{
AddToSchemaErrorsWithMemberInfo(Strings.Mapping_InvalidContent_StorageEntityContainer, storageEntityContainerName,
StorageMappingErrorCode.InvalidEntityContainer, m_sourceLocation, navLineInfo, m_parsingErrors);
}
// If the EntityContainerTypes are not found, there is no point in continuing with the parsing.
if ((entityContainerType == null) || (storageEntityContainerType == null))
{
return null;
}
// Create an EntityContainerMapping object to hold the mapping information for this EntityContainer.
// Create a MappingKey and pass it in.
entityContainerMapping = new StorageEntityContainerMapping(entityContainerType, storageEntityContainerType,
m_storageMappingItemCollection, generateUpdateViews /* make validate same as generateUpdateView*/, generateUpdateViews);
entityContainerMapping.StartLineNumber = navLineInfo.LineNumber;
entityContainerMapping.StartLinePosition = navLineInfo.LinePosition;
}
// Load the child nodes for the created EntityContainerMapping.
LoadEntityContainerMappingChildNodes(nav.Clone(), entityContainerMapping, storageEntityContainerType);
return entityContainerMapping;
}
/// <summary>
/// The method loads the child nodes for the EntityContainer Mapping node
/// into the internal datastructures.
/// </summary>
private void LoadEntityContainerMappingChildNodes(XPathNavigator nav, StorageEntityContainerMapping entityContainerMapping, EntityContainer storageEntityContainerType)
{
IXmlLineInfo xmlLineInfoNav = (IXmlLineInfo)nav;
bool anyEntitySetMapped = false;
//If there is no child node for the EntityContainerMapping Element, return.
if (nav.MoveToChild(XPathNodeType.Element))
{
//The valid child nodes for EntityContainerMapping node are various SetMappings( EntitySet, AssociationSet etc ).
//Loop through the child nodes and lod them as children of the EntityContainerMapping object.
do
{
switch (nav.LocalName)
{
case StorageMslConstructs.EntitySetMappingElement:
{
LoadEntitySetMapping(nav.Clone(), entityContainerMapping, storageEntityContainerType);
anyEntitySetMapped = true;
break;
}
case StorageMslConstructs.AssociationSetMappingElement:
{
LoadAssociationSetMapping(nav.Clone(), entityContainerMapping, storageEntityContainerType);
break;
}
case StorageMslConstructs.FunctionImportMappingElement:
{
LoadFunctionImportMapping(nav.Clone(), entityContainerMapping, storageEntityContainerType);
break;
}
default:
AddToSchemaErrors(Strings.Mapping_InvalidContent_Container_SubElement,
StorageMappingErrorCode.SetMappingExpected, m_sourceLocation, xmlLineInfoNav, m_parsingErrors);
break;
}
} while (nav.MoveToNext(XPathNodeType.Element));
}
//If the EntityContainer contains entity sets but they are not mapped then we should add an error
if (entityContainerMapping.EdmEntityContainer.BaseEntitySets.Count != 0 && !anyEntitySetMapped)
{
AddToSchemaErrorsWithMemberInfo(Strings.ViewGen_Missing_Sets_Mapping,
entityContainerMapping.EdmEntityContainer.Name, StorageMappingErrorCode.EmptyContainerMapping,
this.m_sourceLocation, xmlLineInfoNav, m_parsingErrors);
return;
}
ValidateFunctionAssociationFunctionMappingUnique(nav.Clone(), entityContainerMapping);
ValidateModificationFunctionMappingConsistentForAssociations(nav.Clone(), entityContainerMapping);
ValidateQueryViewsClosure(nav.Clone(), entityContainerMapping);
ValidateEntitySetFunctionMappingClosure(nav.Clone(), entityContainerMapping);
// The fileName field in this class will always have absolute path since StorageMappingItemCollection would have already done it while
// preparing the filePaths.
entityContainerMapping.SourceLocation = m_sourceLocation;
}
/// <summary>
/// Validates that collocated association sets are consistently mapped for each entity set (all operations or none). In the case
/// of relationships between sub-types of an entity set, ensures the relationship mapping is legal.
/// </summary>
/// <param name="nav"></param>
/// <param name="entityContainerMapping"></param>
private void ValidateModificationFunctionMappingConsistentForAssociations(XPathNavigator nav, StorageEntityContainerMapping entityContainerMapping)
{
foreach (StorageEntitySetMapping entitySetMapping in entityContainerMapping.EntitySetMaps)
{
if (entitySetMapping.ModificationFunctionMappings.Count > 0)
{
// determine the set of association sets that should be mapped for every operation
Set<AssociationSetEnd> expectedEnds = new Set<AssociationSetEnd>(
entitySetMapping.ImplicitlyMappedAssociationSetEnds).MakeReadOnly();
// check that each operation covers each association set
foreach (StorageEntityTypeModificationFunctionMapping entityTypeMapping in entitySetMapping.ModificationFunctionMappings)
{
if (null != entityTypeMapping.DeleteFunctionMapping)
{
ValidateModificationFunctionMappingConsistentForAssociations(nav, entitySetMapping, entityTypeMapping,
entityTypeMapping.DeleteFunctionMapping,
expectedEnds, StorageMslConstructs.DeleteFunctionElement);
}
if (null != entityTypeMapping.InsertFunctionMapping)
{
ValidateModificationFunctionMappingConsistentForAssociations(nav, entitySetMapping, entityTypeMapping,
entityTypeMapping.InsertFunctionMapping,
expectedEnds, StorageMslConstructs.InsertFunctionElement);
}
if (null != entityTypeMapping.UpdateFunctionMapping)
{
ValidateModificationFunctionMappingConsistentForAssociations(nav, entitySetMapping, entityTypeMapping,
entityTypeMapping.UpdateFunctionMapping,
expectedEnds, StorageMslConstructs.UpdateFunctionElement);
}
}
}
}
}
private void ValidateModificationFunctionMappingConsistentForAssociations(
XPathNavigator nav,
StorageEntitySetMapping entitySetMapping,
StorageEntityTypeModificationFunctionMapping entityTypeMapping,
StorageModificationFunctionMapping functionMapping,
Set<AssociationSetEnd> expectedEnds, string elementName)
{
IXmlLineInfo xmlLineInfoNav = (IXmlLineInfo)nav;
// check that all expected association sets are mapped for in this function mapping
Set<AssociationSetEnd> actualEnds = new Set<AssociationSetEnd>(functionMapping.CollocatedAssociationSetEnds);
actualEnds.MakeReadOnly();
// check that all required ends are present
foreach (AssociationSetEnd expectedEnd in expectedEnds)
{
// check that the association set is required based on the entity type
if (MetadataHelper.IsAssociationValidForEntityType(expectedEnd, entityTypeMapping.EntityType))
{
if (!actualEnds.Contains(expectedEnd))
{
AddToSchemaErrorWithMessage(Strings.Mapping_ModificationFunction_AssociationSetNotMappedForOperation(
entitySetMapping.Set.Name,
expectedEnd.ParentAssociationSet.Name,
elementName,
entityTypeMapping.EntityType.FullName),
StorageMappingErrorCode.InvalidModificationFunctionMappingAssociationSetNotMappedForOperation,
m_sourceLocation,
xmlLineInfoNav,
m_parsingErrors);
}
}
}
// check that no ends with invalid types are included
foreach (AssociationSetEnd actualEnd in actualEnds)
{
if (!MetadataHelper.IsAssociationValidForEntityType(actualEnd, entityTypeMapping.EntityType))
{
AddToSchemaErrorWithMessage(Strings.Mapping_ModificationFunction_AssociationEndMappingInvalidForEntityType(
entityTypeMapping.EntityType.FullName,
actualEnd.ParentAssociationSet.Name,
MetadataHelper.GetEntityTypeForEnd(MetadataHelper.GetOppositeEnd(actualEnd).CorrespondingAssociationEndMember).FullName),
StorageMappingErrorCode.InvalidModificationFunctionMappingAssociationEndMappingInvalidForEntityType,
m_sourceLocation,
xmlLineInfoNav,
m_parsingErrors);
}
}
}
/// <summary>
/// Validates that association sets are only mapped once.
/// </summary>
/// <param name="nav"></param>
/// <param name="entityContainerMapping">Container to validate</param>
private void ValidateFunctionAssociationFunctionMappingUnique(XPathNavigator nav, StorageEntityContainerMapping entityContainerMapping)
{
Dictionary<EntitySetBase, int> mappingCounts = new Dictionary<EntitySetBase, int>();
// Walk through all entity set mappings
foreach (StorageEntitySetMapping entitySetMapping in entityContainerMapping.EntitySetMaps)
{
if (entitySetMapping.ModificationFunctionMappings.Count > 0)
{
// Get set of association sets implicitly mapped associations to avoid double counting
Set<EntitySetBase> associationSets = new Set<EntitySetBase>();
foreach (AssociationSetEnd end in entitySetMapping.ImplicitlyMappedAssociationSetEnds)
{
associationSets.Add(end.ParentAssociationSet);
}
foreach (EntitySetBase associationSet in associationSets)
{
IncrementCount(mappingCounts, associationSet);
}
}
}
// Walk through all association set mappings
foreach (StorageAssociationSetMapping associationSetMapping in entityContainerMapping.RelationshipSetMaps)
{
if (null != associationSetMapping.ModificationFunctionMapping)
{
IncrementCount(mappingCounts, associationSetMapping.Set);
}
}
// Check for redundantly mapped association sets
List<string> violationNames = new List<string>();
foreach (KeyValuePair<EntitySetBase, int> mappingCount in mappingCounts)
{
if (mappingCount.Value > 1)
{
violationNames.Add(mappingCount.Key.Name);
}
}
if (0 < violationNames.Count)
{
// Warn the user that association sets are mapped multiple times
AddToSchemaErrorsWithMemberInfo(Strings.Mapping_ModificationFunction_AssociationSetAmbiguous,
StringUtil.ToCommaSeparatedString(violationNames), StorageMappingErrorCode.AmbiguousModificationFunctionMappingForAssociationSet,
m_sourceLocation, (IXmlLineInfo)nav, m_parsingErrors);
}
}
private static void IncrementCount<T>(Dictionary<T, int> counts, T key)
{
int count;
if (counts.TryGetValue(key, out count))
{
count++;
}
else
{
count = 1;
}
counts[key] = count;
}
/// <summary>
/// Validates that all or no related extents have function mappings. If an EntitySet or an AssociationSet has a function mapping,
/// then all the sets that touched the same store tableSet must also have function mappings.
/// </summary>
/// <param name="nav"></param>
/// <param name="entityContainerMapping">Container to validate.</param>
private void ValidateEntitySetFunctionMappingClosure(XPathNavigator nav, StorageEntityContainerMapping entityContainerMapping)
{
// here we build a mapping between the tables and the sets,
// setmapping => typemapping => mappingfragments, foreach mappingfragments we have one Tableset,
// then add the tableset with setmapping to the dictionary
KeyToListMap<EntitySet, StorageSetMapping> setMappingPerTable =
new KeyToListMap<EntitySet, StorageSetMapping>(EqualityComparer<EntitySet>.Default);
// Walk through all set mappings
foreach (var setMapping in entityContainerMapping.AllSetMaps)
{
foreach (var typeMapping in setMapping.TypeMappings)
{
foreach (var fragment in typeMapping.MappingFragments)
{
setMappingPerTable.Add(fragment.TableSet, setMapping);
}
}
}
// Get set of association sets implicitly mapped associations to avoid double counting
Set<EntitySetBase> implicitMappedAssociationSets = new Set<EntitySetBase>();
// Walk through all entity set mappings
foreach (StorageEntitySetMapping entitySetMapping in entityContainerMapping.EntitySetMaps)
{
if (entitySetMapping.ModificationFunctionMappings.Count > 0)
{
foreach (AssociationSetEnd end in entitySetMapping.ImplicitlyMappedAssociationSetEnds)
{
implicitMappedAssociationSets.Add(end.ParentAssociationSet);
}
}
}
foreach (var table in setMappingPerTable.Keys)
{
// if any of the sets who touches the same table has modification function,
// then all the sets that touches the same table should have modification function
if (setMappingPerTable.ListForKey(table).Any(s => s.HasModificationFunctionMapping || implicitMappedAssociationSets.Any(aset=> aset == s.Set)) &&
setMappingPerTable.ListForKey(table).Any(s => !s.HasModificationFunctionMapping && !implicitMappedAssociationSets.Any(aset => aset == s.Set)))
{
AddToSchemaErrorsWithMemberInfo(Strings.Mapping_ModificationFunction_MissingSetClosure,
StringUtil.ToCommaSeparatedString(setMappingPerTable.ListForKey(table)
.Where(s => !s.HasModificationFunctionMapping).Select(s=>s.Set.Name)),
StorageMappingErrorCode.MissingSetClosureInModificationFunctionMapping, m_sourceLocation, (IXmlLineInfo)nav
, m_parsingErrors);
}
}
}
private static void ValidateClosureAmongSets(StorageEntityContainerMapping entityContainerMapping, Set<EntitySetBase> sets, Set<EntitySetBase> additionalSetsInClosure)
{
bool nodeFound;
do
{
nodeFound = false;
List<EntitySetBase> newNodes = new List<EntitySetBase>();
// Register entity sets dependencies for association sets
foreach (EntitySetBase entitySetBase in additionalSetsInClosure)
{
AssociationSet associationSet = entitySetBase as AssociationSet;
//Foreign Key Associations do not add to the dependancies
if (associationSet != null
&& !associationSet.ElementType.IsForeignKey)
{
// add the entity sets bound to the end roles to the required list
foreach (AssociationSetEnd end in associationSet.AssociationSetEnds)
{
if (!additionalSetsInClosure.Contains(end.EntitySet))
{
newNodes.Add(end.EntitySet);
}
}
}
}
// Register all association sets referencing known entity sets
foreach (EntitySetBase entitySetBase in entityContainerMapping.EdmEntityContainer.BaseEntitySets)
{
AssociationSet associationSet = entitySetBase as AssociationSet;
//Foreign Key Associations do not add to the dependancies
if (associationSet != null
&& !associationSet.ElementType.IsForeignKey)
{
// check that this association set isn't already in the required set
if (!additionalSetsInClosure.Contains(associationSet))
{
foreach (AssociationSetEnd end in associationSet.AssociationSetEnds)
{
if (additionalSetsInClosure.Contains(end.EntitySet))
{
// this association set must be added to the required list if
// any of its ends are in that list
newNodes.Add(associationSet);
break; // no point adding the association set twice
}
}
}
}
}
if (0 < newNodes.Count)
{
nodeFound = true;
additionalSetsInClosure.AddRange(newNodes);
}
}
while (nodeFound);
additionalSetsInClosure.Subtract(sets);
}
/// <summary>
/// Validates that all or no related extents have query views defined. If an extent has a query view defined, then
/// all related extents must also have query views.
/// </summary>
/// <param name="nav"></param>
/// <param name="entityContainerMapping">Container to validate.</param>
private void ValidateQueryViewsClosure(XPathNavigator nav, StorageEntityContainerMapping entityContainerMapping)
{
//If there is no query view defined, no need to validate
if (!m_hasQueryViews)
{
return;
}
// Check that query views apply to complete subgraph by tracking which extents have query
// mappings and which extents must include query views
Set<EntitySetBase> setsWithQueryViews = new Set<EntitySetBase>();
Set<EntitySetBase> setsRequiringQueryViews = new Set<EntitySetBase>();
// Walk through all set mappings
foreach (StorageSetMapping setMapping in entityContainerMapping.AllSetMaps)
{
if (setMapping.QueryView != null)
{
// a function mapping exists for this entity set
setsWithQueryViews.Add(setMapping.Set);
}
}
// Initialize sets requiring function mapping with the sets that are actually function mapped
setsRequiringQueryViews.AddRange(setsWithQueryViews);
ValidateClosureAmongSets(entityContainerMapping, setsWithQueryViews, setsRequiringQueryViews);
// Check that no required entity or association sets are missing
if (0 < setsRequiringQueryViews.Count)
{
AddToSchemaErrorsWithMemberInfo(Strings.Mapping_Invalid_Query_Views_MissingSetClosure,
StringUtil.ToCommaSeparatedString(setsRequiringQueryViews),
StorageMappingErrorCode.MissingSetClosureInQueryViews, m_sourceLocation, (IXmlLineInfo)nav
, m_parsingErrors);
}
}
/// <summary>
/// The method loads the child nodes for the EntitySet Mapping node
/// into the internal datastructures.
/// </summary>
/// <param name="nav"></param>
/// <param name="entityContainerMapping"></param>
/// <param name="storageEntityContainerType"></param>
private void LoadEntitySetMapping(XPathNavigator nav, StorageEntityContainerMapping entityContainerMapping, EntityContainer storageEntityContainerType)
{
//Get the EntitySet name
string entitySetName = GetAliasResolvedAttributeValue(nav.Clone(), StorageMslConstructs.EntitySetMappingNameAttribute);
//Get the EntityType name, need to parse it if the mapping information is being specified for multiple types
string entityTypeName = StorageMappingItemLoader.GetAttributeValue(nav.Clone(), StorageMslConstructs.EntitySetMappingTypeNameAttribute);
//Get the table name. This might be emptystring since the user can have a TableMappingFragment instead of this.
string tableName = GetAliasResolvedAttributeValue(nav.Clone(), StorageMslConstructs.EntitySetMappingStoreEntitySetAttribute);
bool distinctFlag = GetBoolAttributeValue(nav.Clone(), StorageMslConstructs.MappingFragmentMakeColumnsDistinctAttribute, false /*default value*/);
EntitySet entitySet;
// First check to see if the Entity Set Mapping is already specified. It can be specified, in the same schema file later on
// on a totally different file. Since we support partial mapping, we should just add mapping fragments or entity type
// mappings to the existing entity set mapping
StorageEntitySetMapping setMapping = (StorageEntitySetMapping)entityContainerMapping.GetEntitySetMapping(entitySetName);
// Update the info about the schema element
IXmlLineInfo navLineInfo = (IXmlLineInfo)nav;
if (setMapping == null)
{
//Try to find the EntitySet with the given name in the EntityContainer.
if (!entityContainerMapping.EdmEntityContainer.TryGetEntitySetByName(entitySetName, /*ignoreCase*/ false, out entitySet))
{
//If no EntitySet with the given name exists, than add a schema error and return
AddToSchemaErrorsWithMemberInfo(Strings.Mapping_InvalidContent_Entity_Set, entitySetName,
StorageMappingErrorCode.InvalidEntitySet, m_sourceLocation, navLineInfo, m_parsingErrors);
//There is no point in continuing the loding of this EntitySetMapping if the EntitySet is not found
return;
}
//Create the EntitySet Mapping which contains the mapping information for EntitySetMap.
setMapping = new StorageEntitySetMapping(entitySet, entityContainerMapping);
}
else
{
entitySet = (EntitySet)setMapping.Set;
}
//Set the Start Line Information on Fragment
setMapping.StartLineNumber = navLineInfo.LineNumber;
setMapping.StartLinePosition = navLineInfo.LinePosition;
entityContainerMapping.AddEntitySetMapping(setMapping);
//If the TypeName was not specified as an attribute, than an EntityTypeMapping element should be present
if (String.IsNullOrEmpty(entityTypeName))
{
if (nav.MoveToChild(XPathNodeType.Element))
{
do
{
switch (nav.LocalName)
{
case StorageMslConstructs.EntityTypeMappingElement:
{
//TableName could also be specified on EntityTypeMapping element
tableName = GetAliasResolvedAttributeValue(nav.Clone(), StorageMslConstructs.EntityTypeMappingStoreEntitySetAttribute);
//Load the EntityTypeMapping into memory.
LoadEntityTypeMapping(nav.Clone(), setMapping, tableName, storageEntityContainerType, false /*No distinct flag so far*/, entityContainerMapping.GenerateUpdateViews);
break;
}
case StorageMslConstructs.QueryViewElement:
{
if (!(String.IsNullOrEmpty(tableName)))
{
AddToSchemaErrorsWithMemberInfo(Strings.Mapping_TableName_QueryView, entitySetName,
StorageMappingErrorCode.TableNameAttributeWithQueryView, m_sourceLocation, navLineInfo, m_parsingErrors);
return;
}
//Load the Query View into the set mapping,
//if you get an error, return immediately since
//you go on, you could be giving lot of dubious errors
if(!LoadQueryView(nav.Clone(), setMapping))
{
return;
}
break;
}
default:
AddToSchemaErrors(Strings.Mapping_InvalidContent_TypeMapping_QueryView,
StorageMappingErrorCode.InvalidContent, m_sourceLocation, navLineInfo, m_parsingErrors);
break;
}
} while (nav.MoveToNext(XPathNodeType.Element));
}
}
else
{
//Load the EntityTypeMapping into memory.
LoadEntityTypeMapping(nav.Clone(), setMapping, tableName, storageEntityContainerType, distinctFlag, entityContainerMapping.GenerateUpdateViews);
}
ValidateAllEntityTypesHaveFunctionMapping(nav.Clone(), setMapping);
//Add a schema error if the set mapping has no content
if (setMapping.HasNoContent)
{
AddToSchemaErrorsWithMemberInfo(Strings.Mapping_InvalidContent_Emtpty_SetMap, entitySet.Name,
StorageMappingErrorCode.EmptySetMapping, m_sourceLocation, navLineInfo, m_parsingErrors);
}
}
// Ensure if any type has a function mapping, all types have function mappings
private void ValidateAllEntityTypesHaveFunctionMapping(XPathNavigator nav, StorageEntitySetMapping setMapping)
{
Set<EdmType> functionMappedTypes = new Set<EdmType>();
foreach (StorageEntityTypeModificationFunctionMapping modificationFunctionMapping in setMapping.ModificationFunctionMappings)
{
functionMappedTypes.Add(modificationFunctionMapping.EntityType);
}
if (0 < functionMappedTypes.Count)
{
Set<EdmType> unmappedTypes = new Set<EdmType>(MetadataHelper.GetTypeAndSubtypesOf(setMapping.Set.ElementType, EdmItemCollection, false /*includeAbstractTypes*/));
unmappedTypes.Subtract(functionMappedTypes);
// Remove abstract types
Set<EdmType> abstractTypes = new Set<EdmType>();
foreach (EntityType unmappedType in unmappedTypes)
{
if (unmappedType.Abstract)
{
abstractTypes.Add(unmappedType);
}
}
unmappedTypes.Subtract(abstractTypes);
// See if there are any remaining entity types requiring function mapping
if (0 < unmappedTypes.Count)
{
AddToSchemaErrorsWithMemberInfo(Strings.Mapping_ModificationFunction_MissingEntityType,
StringUtil.ToCommaSeparatedString(unmappedTypes),
StorageMappingErrorCode.MissingModificationFunctionMappingForEntityType, m_sourceLocation, (IXmlLineInfo)nav
, m_parsingErrors);
}
}
}
private bool TryParseEntityTypeAttribute(
XPathNavigator nav,
EntityType rootEntityType,
Func<EntityType, string> typeNotAssignableMessage,
out Set<EntityType> isOfTypeEntityTypes,
out Set<EntityType> entityTypes)
{
IXmlLineInfo xmlLineInfoNav = (IXmlLineInfo)nav;
string entityTypeAttribute = GetAttributeValue(nav.Clone(), StorageMslConstructs.EntitySetMappingTypeNameAttribute);
isOfTypeEntityTypes = new Set<EntityType>();
entityTypes = new Set<EntityType>();
// get components of type declaration
var entityTypeNames = entityTypeAttribute.Split(StorageMslConstructs.TypeNameSperator).Select(s => s.Trim());
// figure out each component
foreach (var name in entityTypeNames)
{
bool isTypeOf = name.StartsWith(StorageMslConstructs.IsTypeOf, StringComparison.Ordinal);
string entityTypeName;
if (isTypeOf)
{
// get entityTypeName of OfType(entityTypeName)
if (!name.EndsWith(StorageMslConstructs.IsTypeOfTerminal, StringComparison.Ordinal))
{
AddToSchemaErrorWithMessage(Strings.Mapping_InvalidContent_IsTypeOfNotTerminated,
StorageMappingErrorCode.InvalidEntityType, m_sourceLocation, xmlLineInfoNav, m_parsingErrors);
// No point in continuing with an error in the entitytype name
return false;
}
entityTypeName = name.Substring(StorageMslConstructs.IsTypeOf.Length);
entityTypeName = entityTypeName.Substring(0, entityTypeName.Length - StorageMslConstructs.IsTypeOfTerminal.Length).Trim();
}
else
{
entityTypeName = name;
}
// resolve aliases
entityTypeName = GetAliasResolvedValue(entityTypeName);
EntityType entityType;
if (!this.EdmItemCollection.TryGetItem<EntityType>(entityTypeName, out entityType))
{
AddToSchemaErrorsWithMemberInfo(Strings.Mapping_InvalidContent_Entity_Type, entityTypeName,
StorageMappingErrorCode.InvalidEntityType, m_sourceLocation, xmlLineInfoNav, m_parsingErrors);
// No point in continuing with an error in the entitytype name
return false;
}
if (!(Helper.IsAssignableFrom(rootEntityType, entityType)))
{
IXmlLineInfo lineInfo = xmlLineInfoNav;
AddToSchemaErrorWithMessage(
typeNotAssignableMessage(entityType),
StorageMappingErrorCode.InvalidEntityType, m_sourceLocation, xmlLineInfoNav, m_parsingErrors);
//no point in continuing with an error in the entitytype name
return false;
}
// Using TypeOf construct on an abstract type that does not have
// any concrete descendants is not allowed
if (entityType.Abstract)
{
if (isTypeOf)
{
IEnumerable<EdmType> typeAndSubTypes = MetadataHelper.GetTypeAndSubtypesOf(entityType, EdmItemCollection, false /*includeAbstractTypes*/);
if (!typeAndSubTypes.GetEnumerator().MoveNext())
{
AddToSchemaErrorsWithMemberInfo(Strings.Mapping_InvalidContent_AbstractEntity_IsOfType, entityType.FullName,
StorageMappingErrorCode.MappingOfAbstractType, m_sourceLocation, xmlLineInfoNav, m_parsingErrors);
return false;
}
}
else
{
AddToSchemaErrorsWithMemberInfo(Strings.Mapping_InvalidContent_AbstractEntity_Type, entityType.FullName,
StorageMappingErrorCode.MappingOfAbstractType, m_sourceLocation, xmlLineInfoNav, m_parsingErrors);
return false;
}
}
// Add type to set
if (isTypeOf)
{
isOfTypeEntityTypes.Add(entityType);
}
else
{
entityTypes.Add(entityType);
}
}
// No failures
return true;
}
/// <summary>
/// The method loads the child nodes for the EntityType Mapping node
/// into the internal datastructures.
/// </summary>
/// <param name="nav"></param>
/// <param name="entitySetMapping"></param>
/// <param name="tableName"></param>
/// <param name="storageEntityContainerType"></param>
private void LoadEntityTypeMapping(XPathNavigator nav, StorageEntitySetMapping entitySetMapping, string tableName, EntityContainer storageEntityContainerType, bool distinctFlagAboveType, bool generateUpdateViews)
{
IXmlLineInfo xmlLineInfoNav = (IXmlLineInfo)nav;
//Create an EntityTypeMapping to hold the information for EntityType mapping.
StorageEntityTypeMapping entityTypeMapping = new StorageEntityTypeMapping(entitySetMapping);
//Get entity types
Set<EntityType> entityTypes;
Set<EntityType> isOfTypeEntityTypes;
EntityType rootEntityType = (EntityType)entitySetMapping.Set.ElementType;
if (!TryParseEntityTypeAttribute(nav.Clone(), rootEntityType,
e => Strings.Mapping_InvalidContent_Entity_Type_For_Entity_Set(e.FullName, rootEntityType.FullName, entitySetMapping.Set.Name),
out isOfTypeEntityTypes,
out entityTypes))
{
// Return if we cannot parse entity types
return;
}
// Register all mapped types
foreach (EntityType entityType in entityTypes)
{
entityTypeMapping.AddType(entityType);
}
foreach (EntityType isOfTypeEntityType in isOfTypeEntityTypes)
{
entityTypeMapping.AddIsOfType(isOfTypeEntityType);
}
//If the table name was not specified on the EntitySetMapping element nor the EntityTypeMapping element
//than a table mapping fragment element should be present
//Loop through the TableMappingFragment elements and add them to EntityTypeMappings
if (String.IsNullOrEmpty(tableName))
{
if (!nav.MoveToChild(XPathNodeType.Element))
return;
do
{
if (nav.LocalName == StorageMslConstructs.ModificationFunctionMappingElement)
{
entitySetMapping.HasModificationFunctionMapping = true;
LoadEntityTypeModificationFunctionMapping(nav.Clone(), entitySetMapping, entityTypeMapping);
}
else if (nav.LocalName != StorageMslConstructs.MappingFragmentElement)
{
AddToSchemaErrors(Strings.Mapping_InvalidContent_Table_Expected,
StorageMappingErrorCode.TableMappingFragmentExpected, m_sourceLocation, xmlLineInfoNav
, m_parsingErrors);
}
else
{
bool distinctFlag = GetBoolAttributeValue(nav.Clone(), StorageMslConstructs.MappingFragmentMakeColumnsDistinctAttribute, false /*default value*/);
if (generateUpdateViews && distinctFlag)
{
AddToSchemaErrors(Strings.Mapping_DistinctFlagInReadWriteContainer,
StorageMappingErrorCode.DistinctFragmentInReadWriteContainer, m_sourceLocation, xmlLineInfoNav, m_parsingErrors);
}
tableName = GetAliasResolvedAttributeValue(nav.Clone(), StorageMslConstructs.MappingFragmentStoreEntitySetAttribute);
StorageMappingFragment fragment = LoadMappingFragment(nav.Clone(), entityTypeMapping, tableName, storageEntityContainerType, distinctFlag);
//The fragment can be null in the cases of validation errors.
if (fragment != null)
{
entityTypeMapping.AddFragment(fragment);
}
}
} while (nav.MoveToNext(XPathNodeType.Element));
}
else
{
if (nav.LocalName == StorageMslConstructs.ModificationFunctionMappingElement)
{
// function mappings cannot exist in the context of a table mapping
AddToSchemaErrors(Strings.Mapping_ModificationFunction_In_Table_Context,
StorageMappingErrorCode.InvalidTableNameAttributeWithModificationFunctionMapping,
m_sourceLocation, xmlLineInfoNav
, m_parsingErrors);
}
if (generateUpdateViews && distinctFlagAboveType)
{
AddToSchemaErrors(Strings.Mapping_DistinctFlagInReadWriteContainer,
StorageMappingErrorCode.DistinctFragmentInReadWriteContainer, m_sourceLocation, xmlLineInfoNav, m_parsingErrors);
}
StorageMappingFragment fragment = LoadMappingFragment(nav.Clone(), entityTypeMapping, tableName,
storageEntityContainerType, distinctFlagAboveType);
//The fragment can be null in the cases of validation errors.
if (fragment != null)
{
entityTypeMapping.AddFragment(fragment);
}
}
entitySetMapping.AddTypeMapping(entityTypeMapping);
}
/// <summary>
/// Loads modification function mappings for entity type.
/// </summary>
/// <param name="nav"></param>
/// <param name="entitySetMapping"></param>
/// <param name="entityTypeMapping"></param>
private void LoadEntityTypeModificationFunctionMapping(
XPathNavigator nav,
StorageEntitySetMapping entitySetMapping,
StorageEntityTypeMapping entityTypeMapping)
{
IXmlLineInfo xmlLineInfoNav = (IXmlLineInfo)nav;
// Function mappings can apply only to a single type.
if (entityTypeMapping.IsOfTypes.Count != 0 || entityTypeMapping.Types.Count != 1)
{
AddToSchemaErrors(Strings.Mapping_ModificationFunction_Multiple_Types,
StorageMappingErrorCode.InvalidModificationFunctionMappingForMultipleTypes,
m_sourceLocation, xmlLineInfoNav, m_parsingErrors);
return;
}
EntityType entityType = (EntityType)entityTypeMapping.Types[0];
//Function Mapping is not allowed to be defined for Abstract Types
if (entityType.Abstract)
{
AddToSchemaErrorsWithMemberInfo(Strings.Mapping_InvalidContent_AbstractEntity_FunctionMapping, entityType.FullName,
StorageMappingErrorCode.MappingOfAbstractType, m_sourceLocation, xmlLineInfoNav, m_parsingErrors);
return;
}
// check that no mapping exists for this entity type already
foreach (StorageEntityTypeModificationFunctionMapping existingMapping in entitySetMapping.ModificationFunctionMappings)
{
if (existingMapping.EntityType.Equals(entityType))
{
AddToSchemaErrorsWithMemberInfo(Strings.Mapping_ModificationFunction_RedundantEntityTypeMapping,
entityType.Name, StorageMappingErrorCode.RedundantEntityTypeMappingInModificationFunctionMapping, m_sourceLocation, xmlLineInfoNav
, m_parsingErrors);
return;
}
}
// create function loader
ModificationFunctionMappingLoader functionLoader = new ModificationFunctionMappingLoader(this, entitySetMapping.Set);
// Load all function definitions (for insert, delete and update)
StorageModificationFunctionMapping deleteFunctionMapping = null;
StorageModificationFunctionMapping insertFunctionMapping = null;
StorageModificationFunctionMapping updateFunctionMapping = null;
if (nav.MoveToChild(XPathNodeType.Element))
{
do
{
switch (nav.LocalName)
{
case StorageMslConstructs.DeleteFunctionElement:
deleteFunctionMapping = functionLoader.LoadEntityTypeModificationFunctionMapping(nav.Clone(), entitySetMapping.Set, false, true, entityType);
break;
case StorageMslConstructs.InsertFunctionElement:
insertFunctionMapping = functionLoader.LoadEntityTypeModificationFunctionMapping(nav.Clone(), entitySetMapping.Set, true, false, entityType);
break;
case StorageMslConstructs.UpdateFunctionElement:
updateFunctionMapping = functionLoader.LoadEntityTypeModificationFunctionMapping(nav.Clone(), entitySetMapping.Set, true, true, entityType);
break;
}
} while (nav.MoveToNext(XPathNodeType.Element));
}
// Ensure that assocation set end mappings bind to the same end (e.g., in Person Manages Person
// self-association, ensure that the manager end or the report end is mapped but not both)
IEnumerable<StorageModificationFunctionParameterBinding> parameterList = new List<StorageModificationFunctionParameterBinding>();
if (null != deleteFunctionMapping)
{
parameterList = Helper.Concat(parameterList, deleteFunctionMapping.ParameterBindings);
}
if (null != insertFunctionMapping)
{
parameterList = Helper.Concat(parameterList, insertFunctionMapping.ParameterBindings);
}
if (null != updateFunctionMapping)
{
parameterList = Helper.Concat(parameterList, updateFunctionMapping.ParameterBindings);
}
var associationEnds = new Dictionary<AssociationSet, AssociationEndMember>();
foreach (StorageModificationFunctionParameterBinding parameterBinding in parameterList)
{
if (null != parameterBinding.MemberPath.AssociationSetEnd)
{
AssociationSet associationSet = parameterBinding.MemberPath.AssociationSetEnd.ParentAssociationSet;
// the "end" corresponds to the second member in the path, e.g.
// ID<-Manager where Manager is the end
AssociationEndMember currentEnd = parameterBinding.MemberPath.AssociationSetEnd.CorrespondingAssociationEndMember;
AssociationEndMember existingEnd;
if (associationEnds.TryGetValue(associationSet, out existingEnd) &&
existingEnd != currentEnd)
{
AddToSchemaErrorWithMessage(Strings.Mapping_ModificationFunction_MultipleEndsOfAssociationMapped(
currentEnd.Name, existingEnd.Name, associationSet.Name),
StorageMappingErrorCode.InvalidModificationFunctionMappingMultipleEndsOfAssociationMapped, m_sourceLocation, xmlLineInfoNav, m_parsingErrors);
return;
}
else
{
associationEnds[associationSet] = currentEnd;
}
}
}
// Register the function mapping on the entity set mapping
StorageEntityTypeModificationFunctionMapping mapping = new StorageEntityTypeModificationFunctionMapping(
entityType, deleteFunctionMapping, insertFunctionMapping, updateFunctionMapping);
entitySetMapping.AddModificationFunctionMapping(mapping);
}
/// <summary>
/// The method loads the query view for the Set Mapping node
/// into the internal datastructures.
/// </summary>
private bool LoadQueryView(XPathNavigator nav, StorageSetMapping setMapping)
{
Debug.Assert(nav.LocalName == StorageMslConstructs.QueryViewElement);
string queryView = nav.Value;
bool includeSubtypes = false;
string typeNameString = StorageMappingItemLoader.GetAttributeValue(nav.Clone(), StorageMslConstructs.EntitySetMappingTypeNameAttribute);
if (typeNameString != null)
{
typeNameString = typeNameString.Trim();
}
if (setMapping.QueryView == null)
{
// QV must be the special-case first view.
if (typeNameString != null)
{
AddToSchemaErrorsWithMemberInfo(val => Strings.Mapping_TypeName_For_First_QueryView,
setMapping.Set.Name, StorageMappingErrorCode.TypeNameForFirstQueryView,
m_sourceLocation, (IXmlLineInfo)nav, m_parsingErrors);
return false;
}
if (String.IsNullOrEmpty(queryView))
{
AddToSchemaErrorsWithMemberInfo(Strings.Mapping_Empty_QueryView,
setMapping.Set.Name, StorageMappingErrorCode.EmptyQueryView,
m_sourceLocation, (IXmlLineInfo)nav, m_parsingErrors);
return false;
}
setMapping.QueryView = queryView;
this.m_hasQueryViews = true;
return true;
}
else
{
//QV must be typeof or typeofonly view
if (typeNameString == null || typeNameString.Trim().Length == 0)
{
AddToSchemaErrorsWithMemberInfo(Strings.Mapping_QueryView_TypeName_Not_Defined,
setMapping.Set.Name, StorageMappingErrorCode.NoTypeNameForTypeSpecificQueryView,
m_sourceLocation, (IXmlLineInfo)nav, m_parsingErrors);
return false;
}
//Get entity types
Set<EntityType> entityTypes;
Set<EntityType> isOfTypeEntityTypes;
EntityType rootEntityType = (EntityType)setMapping.Set.ElementType;
if (!TryParseEntityTypeAttribute(nav.Clone(), rootEntityType,
e => Strings.Mapping_InvalidContent_Entity_Type_For_Entity_Set(e.FullName, rootEntityType.FullName, setMapping.Set.Name),
out isOfTypeEntityTypes,
out entityTypes))
{
// Return if we cannot parse entity types
return false;
}
Debug.Assert(isOfTypeEntityTypes.Count > 0 || entityTypes.Count > 0);
Debug.Assert(!(isOfTypeEntityTypes.Count > 0 && entityTypes.Count > 0));
EntityType entityType;
if (isOfTypeEntityTypes.Count == 1)
{ //OfType View
entityType = isOfTypeEntityTypes.First();
includeSubtypes = true;
}
else if (entityTypes.Count == 1)
{ //OfTypeOnly View
entityType = entityTypes.First();
includeSubtypes = false;
}
else
{
//More than one type
AddToSchemaErrorsWithMemberInfo(Strings.Mapping_QueryViewMultipleTypeInTypeName, setMapping.Set.ToString(),
StorageMappingErrorCode.TypeNameContainsMultipleTypesForQueryView, m_sourceLocation, (IXmlLineInfo)nav, m_parsingErrors);
return false;
}
//Check if IsTypeOf(A) and A is the base type
if (includeSubtypes && setMapping.Set.ElementType.EdmEquals(entityType))
{ //Don't allow TypeOFOnly(a) if a is a base type.
AddToSchemaErrorWithMemberAndStructure(Strings.Mapping_QueryView_For_Base_Type, entityType.ToString(), setMapping.Set.ToString(),
StorageMappingErrorCode.IsTypeOfQueryViewForBaseType, m_sourceLocation, (IXmlLineInfo)nav, m_parsingErrors);
return false;
}
if (String.IsNullOrEmpty(queryView))
{
if (includeSubtypes)
{
AddToSchemaErrorWithMemberAndStructure(Strings.Mapping_Empty_QueryView_OfType,
entityType.Name, setMapping.Set.Name, StorageMappingErrorCode.EmptyQueryView,
m_sourceLocation, (IXmlLineInfo)nav, m_parsingErrors);
return false;
}
else
{
AddToSchemaErrorWithMemberAndStructure(Strings.Mapping_Empty_QueryView_OfTypeOnly,
setMapping.Set.Name, entityType.Name, StorageMappingErrorCode.EmptyQueryView,
m_sourceLocation, (IXmlLineInfo)nav, m_parsingErrors);
return false;
}
}
//Add it to the QV cache
Triple key = new Triple(setMapping.Set, new Pair<EntityTypeBase, bool>(entityType, includeSubtypes));
if (setMapping.ContainsTypeSpecificQueryView(key))
{ //two QVs for the same type
EdmSchemaError error = null;
if (includeSubtypes)
{
error =
new EdmSchemaError(
Strings.Mapping_QueryView_Duplicate_OfType(setMapping.Set, entityType),
(int)StorageMappingErrorCode.QueryViewExistsForEntitySetAndType, EdmSchemaErrorSeverity.Error, m_sourceLocation,
((IXmlLineInfo)nav).LineNumber, ((IXmlLineInfo)nav).LinePosition);
}
else
{
error =
new EdmSchemaError(
Strings.Mapping_QueryView_Duplicate_OfTypeOnly(setMapping.Set, entityType),
(int)StorageMappingErrorCode.QueryViewExistsForEntitySetAndType, EdmSchemaErrorSeverity.Error, m_sourceLocation,
((IXmlLineInfo)nav).LineNumber, ((IXmlLineInfo)nav).LinePosition);
}
m_parsingErrors.Add(error);
return false;
}
setMapping.AddTypeSpecificQueryView(key, queryView);
return true;
}
}
/// <summary>
/// The method loads the child nodes for the AssociationSet Mapping node
/// into the internal datastructures.
/// </summary>
/// <param name="nav"></param>
/// <param name="entityContainerMapping"></param>
/// <param name="storageEntityContainerType"></param>
private void LoadAssociationSetMapping(XPathNavigator nav, StorageEntityContainerMapping entityContainerMapping, EntityContainer storageEntityContainerType)
{
IXmlLineInfo navLineInfo = (IXmlLineInfo)nav;
//Get the AssociationSet name
string associationSetName = GetAliasResolvedAttributeValue(nav.Clone(), StorageMslConstructs.AssociationSetMappingNameAttribute);
//Get the AssociationType name, need to parse it if the mapping information is being specified for multiple types
string associationTypeName = GetAliasResolvedAttributeValue(nav.Clone(), StorageMslConstructs.AssociationSetMappingTypeNameAttribute);
//Get the table name. This might be emptystring since the user can have a TableMappingFragment instead of this.
string tableName = GetAliasResolvedAttributeValue(nav.Clone(), StorageMslConstructs.EntitySetMappingStoreEntitySetAttribute);
//Try to find the AssociationSet with the given name in the EntityContainer.
RelationshipSet relationshipSet;
entityContainerMapping.EdmEntityContainer.TryGetRelationshipSetByName(associationSetName, false /*ignoreCase*/, out relationshipSet);
AssociationSet associationSet = relationshipSet as AssociationSet;
//If no AssociationSet with the given name exists, than Add a schema error and return
if (associationSet == null)
{
AddToSchemaErrorsWithMemberInfo(Strings.Mapping_InvalidContent_Association_Set, associationSetName,
StorageMappingErrorCode.InvalidAssociationSet, m_sourceLocation, navLineInfo, m_parsingErrors);
//There is no point in continuing the loading of association set map if the AssociationSetName has a problem
return;
}
if (associationSet.ElementType.IsForeignKey)
{
ReferentialConstraint constraint = associationSet.ElementType.ReferentialConstraints.Single();
IEnumerable<EdmMember> dependentKeys = MetadataHelper.GetEntityTypeForEnd((AssociationEndMember)constraint.ToRole).KeyMembers;
if (associationSet.ElementType.ReferentialConstraints.Single().ToProperties.All(p => dependentKeys.Contains(p)))
{
EdmSchemaError error = AddToSchemaErrorsWithMemberInfo(Strings.Mapping_InvalidContent_ForeignKey_Association_Set_PKtoPK, associationSetName,
StorageMappingErrorCode.InvalidAssociationSet, m_sourceLocation, navLineInfo, m_parsingErrors);
//Downgrade to a warning if the foreign key constraint is between keys (for back-compat reasons)
error.Severity = EdmSchemaErrorSeverity.Warning;
}
else
{
AddToSchemaErrorsWithMemberInfo(Strings.Mapping_InvalidContent_ForeignKey_Association_Set, associationSetName,
StorageMappingErrorCode.InvalidAssociationSet, m_sourceLocation, navLineInfo, m_parsingErrors);
}
return;
}
if (entityContainerMapping.ContainsAssociationSetMapping(associationSet))
{
//Can not add this set mapping since our storage dictionary won't allow
//duplicate maps
AddToSchemaErrorsWithMemberInfo(Strings.Mapping_Duplicate_CdmAssociationSet_StorageMap, associationSetName,
StorageMappingErrorCode.DuplicateSetMapping, m_sourceLocation, navLineInfo, m_parsingErrors);
return;
}
//Create the AssociationSet Mapping which contains the mapping information for association set.
StorageAssociationSetMapping setMapping = new StorageAssociationSetMapping(associationSet, entityContainerMapping);
//Set the Start Line Information on Fragment
setMapping.StartLineNumber = navLineInfo.LineNumber;
setMapping.StartLinePosition = navLineInfo.LinePosition;
if (!nav.MoveToChild(XPathNodeType.Element))
{
AddToSchemaErrorsWithMemberInfo(Strings.Mapping_InvalidContent_Emtpty_SetMap, associationSet.Name,
StorageMappingErrorCode.EmptySetMapping, m_sourceLocation, navLineInfo, m_parsingErrors);
return;
}
entityContainerMapping.AddAssociationSetMapping(setMapping);
//If there is a query view it has to be the first element
if (nav.LocalName == StorageMslConstructs.QueryViewElement)
{
if (!(String.IsNullOrEmpty(tableName)))
{
AddToSchemaErrorsWithMemberInfo(Strings.Mapping_TableName_QueryView, associationSetName,
StorageMappingErrorCode.TableNameAttributeWithQueryView, m_sourceLocation, navLineInfo, m_parsingErrors);
return;
}
//Load the Query View into the set mapping,
//if you get an error, return immediately since
//you go on, you could be giving lot of dubious errors
if (!LoadQueryView(nav.Clone(), setMapping))
{
return;
}
//If there are no more elements just return
if (!nav.MoveToNext(XPathNodeType.Element))
{
return;
}
}
if ((nav.LocalName == StorageMslConstructs.EndPropertyMappingElement) ||
(nav.LocalName == StorageMslConstructs.ModificationFunctionMappingElement))
{
if ((String.IsNullOrEmpty(associationTypeName)))
{
AddToSchemaErrors(Strings.Mapping_InvalidContent_Association_Type_Empty,
StorageMappingErrorCode.InvalidAssociationType, m_sourceLocation, navLineInfo, m_parsingErrors);
return;
}
//Load the AssociationTypeMapping into memory.
LoadAssociationTypeMapping(nav.Clone(), setMapping, associationTypeName, tableName, storageEntityContainerType);
}
else if (nav.LocalName == StorageMslConstructs.ConditionElement)
{
AddToSchemaErrorsWithMemberInfo(Strings.Mapping_InvalidContent_AssociationSet_Condition, associationSetName,
StorageMappingErrorCode.InvalidContent, m_sourceLocation, navLineInfo, m_parsingErrors);
return;
}
else
{
Debug.Assert(false, "XSD validation should ensure this");
}
}
#region LoadFunctionImportMapping implementation
/// <summary>
/// The method loads a function import mapping element
/// </summary>
/// <param name="nav"></param>
/// <param name="entityContainerMapping"></param>
/// <param name="storageEntityContainerType"></param>
private void LoadFunctionImportMapping(XPathNavigator nav, StorageEntityContainerMapping entityContainerMapping, EntityContainer storageEntityContainerType)
{
IXmlLineInfo lineInfo = (IXmlLineInfo)(nav.Clone());
// Get target (store) function
EdmFunction targetFunction;
if (!TryGetFunctionImportStoreFunction(nav, out targetFunction))
{
return;
}
// Get source (model) function
EdmFunction functionImport;
if (!TryGetFunctionImportModelFunction(nav, entityContainerMapping, out functionImport))
{
return;
}
// Validate composability alignment of function import and target function.
if (!functionImport.IsComposableAttribute && targetFunction.IsComposableAttribute)
{
AddToSchemaErrorWithMessage(Strings.Mapping_FunctionImport_TargetFunctionMustBeNonComposable(functionImport.FullName, targetFunction.FullName),
StorageMappingErrorCode.MappingFunctionImportTargetFunctionMustBeNonComposable,
m_sourceLocation, lineInfo, m_parsingErrors);
return;
}
else if (functionImport.IsComposableAttribute && !targetFunction.IsComposableAttribute)
{
AddToSchemaErrorWithMessage(Strings.Mapping_FunctionImport_TargetFunctionMustBeComposable(functionImport.FullName, targetFunction.FullName),
StorageMappingErrorCode.MappingFunctionImportTargetFunctionMustBeComposable,
m_sourceLocation, lineInfo, m_parsingErrors);
return;
}
// Validate parameters are compatible between the store and model functions
ValidateFunctionImportMappingParameters(nav, targetFunction, functionImport);
// Process type mapping information
var typeMappingsList = new List<List<FunctionImportStructuralTypeMapping>>();
if (nav.MoveToChild(XPathNodeType.Element))
{
int resultSetIndex = 0;
do
{
if (nav.LocalName == StorageMslConstructs.FunctionImportMappingResultMapping)
{
List<FunctionImportStructuralTypeMapping> typeMappings = GetFunctionImportMappingResultMapping(nav.Clone(), lineInfo, targetFunction, functionImport, resultSetIndex, typeMappingsList);
typeMappingsList.Add(typeMappings);
}
resultSetIndex++;
} while (nav.MoveToNext(XPathNodeType.Element));
}
// Verify that there are the right number of result mappings
if (typeMappingsList.Count > 0 && typeMappingsList.Count != functionImport.ReturnParameters.Count)
{
AddToSchemaErrors(Strings.Mapping_FunctionImport_ResultMappingCountDoesNotMatchResultCount(functionImport.Identity),
StorageMappingErrorCode.FunctionResultMappingCountMismatch, m_sourceLocation, lineInfo, m_parsingErrors);
return;
}
if (functionImport.IsComposableAttribute)
{
//
// Add composable function import mapping to the list.
//
// Function mapping is allowed only for TVFs on the s-space.
var cTypeTargetFunction = this.StoreItemCollection.ConvertToCTypeFunction(targetFunction);
var cTypeTvfElementType = System.Data.Common.TypeHelpers.GetTvfReturnType(cTypeTargetFunction);
var sTypeTvfElementType = System.Data.Common.TypeHelpers.GetTvfReturnType(targetFunction);
if (cTypeTvfElementType == null)
{
Debug.Assert(sTypeTvfElementType == null, "sTypeTvfElementType == null");
AddToSchemaErrors(Strings.Mapping_FunctionImport_ResultMapping_InvalidSType(functionImport.Identity),
StorageMappingErrorCode.MappingFunctionImportTVFExpected, m_sourceLocation, lineInfo, m_parsingErrors);
return;
}
Debug.Assert(functionImport.ReturnParameters.Count == 1, "functionImport.ReturnParameters.Count == 1 for a composable function import.");
var typeMappings = typeMappingsList.Count > 0 ? typeMappingsList[0] : new List<FunctionImportStructuralTypeMapping>();
FunctionImportMappingComposable mapping = null;
EdmType resultType;
if (MetadataHelper.TryGetFunctionImportReturnType<EdmType>(functionImport, 0, out resultType))
{
if (Helper.IsStructuralType(resultType))
{
if (!TryCreateFunctionImportMappingComposableWithStructuralResult(
functionImport,
cTypeTargetFunction,
typeMappings,
(StructuralType)resultType,
cTypeTvfElementType,
sTypeTvfElementType,
lineInfo,
out mapping))
{
return;
}
}
else
{
Debug.Assert(TypeSemantics.IsScalarType(resultType), "TypeSemantics.IsScalarType(resultType)");
Debug.Assert(typeMappings.Count == 0, "typeMappings.Count == 0");
if (!TryCreateFunctionImportMappingComposableWithScalarResult(
functionImport,
cTypeTargetFunction,
targetFunction,
resultType,
cTypeTvfElementType,
sTypeTvfElementType,
lineInfo,
out mapping))
{
return;
}
}
}
else
{
Debug.Fail("Composable function import must have return type.");
}
Debug.Assert(mapping != null, "mapping != null");
entityContainerMapping.AddFunctionImportMapping(functionImport, mapping);
}
else
{
//
// Add non-composable function import mapping to the list.
//
var mapping = new FunctionImportMappingNonComposable(functionImport, targetFunction, typeMappingsList, this.EdmItemCollection);
// Verify that all entity types can be produced.
foreach (FunctionImportStructuralTypeMappingKB resultMapping in mapping.ResultMappings)
{
resultMapping.ValidateTypeConditions(/*validateAmbiguity: */false, m_parsingErrors, m_sourceLocation);
}
// Verify that function imports returning abstract types include explicit mappings
for (int i = 0; i < mapping.ResultMappings.Count; i++)
{
EntityType returnEntityType;
if (MetadataHelper.TryGetFunctionImportReturnType<EntityType>(functionImport, i, out returnEntityType) &&
returnEntityType.Abstract &&
mapping.GetResultMapping(i).NormalizedEntityTypeMappings.Count == 0)
{
AddToSchemaErrorWithMemberAndStructure(Strings.Mapping_FunctionImport_ImplicitMappingForAbstractReturnType, returnEntityType.FullName,
functionImport.Identity, StorageMappingErrorCode.MappingOfAbstractType, m_sourceLocation, lineInfo, m_parsingErrors);
}
}
entityContainerMapping.AddFunctionImportMapping(functionImport, mapping);
}
}
private bool TryGetFunctionImportStoreFunction(XPathNavigator nav, out EdmFunction targetFunction)
{
IXmlLineInfo xmlLineInfoNav = (IXmlLineInfo)nav;
targetFunction = null;
// Get the function name
string functionName = GetAliasResolvedAttributeValue(nav.Clone(), StorageMslConstructs.FunctionImportMappingFunctionNameAttribute);
// Try to find the function definition
ReadOnlyCollection<EdmFunction> functionOverloads = this.StoreItemCollection.GetFunctions(functionName);
if (functionOverloads.Count == 0)
{
AddToSchemaErrorWithMessage(Strings.Mapping_FunctionImport_StoreFunctionDoesNotExist(functionName),
StorageMappingErrorCode.MappingFunctionImportStoreFunctionDoesNotExist,
m_sourceLocation, xmlLineInfoNav, m_parsingErrors);
return false;
}
else if (functionOverloads.Count > 1)
{
AddToSchemaErrorWithMessage(Strings.Mapping_FunctionImport_FunctionAmbiguous(functionName),
StorageMappingErrorCode.MappingFunctionImportStoreFunctionAmbiguous,
m_sourceLocation, xmlLineInfoNav, m_parsingErrors);
return false;
}
targetFunction = functionOverloads.Single();
return true;
}
private bool TryGetFunctionImportModelFunction(
XPathNavigator nav,
StorageEntityContainerMapping entityContainerMapping,
out EdmFunction functionImport)
{
IXmlLineInfo xmlLineInfoNav = (IXmlLineInfo)nav;
// Get the function import name
string functionImportName = GetAliasResolvedAttributeValue(nav.Clone(), StorageMslConstructs.FunctionImportMappingFunctionImportNameAttribute);
// Try to find the function import
EntityContainer modelContainer = entityContainerMapping.EdmEntityContainer;
functionImport = null;
foreach (EdmFunction functionImportCandidate in modelContainer.FunctionImports)
{
if (functionImportCandidate.Name == functionImportName)
{
functionImport = functionImportCandidate;
break;
}
}
if (null == functionImport)
{
AddToSchemaErrorWithMessage(Strings.Mapping_FunctionImport_FunctionImportDoesNotExist(functionImportName, entityContainerMapping.EdmEntityContainer.Name),
StorageMappingErrorCode.MappingFunctionImportFunctionImportDoesNotExist,
m_sourceLocation, xmlLineInfoNav, m_parsingErrors);
return false;
}
// check that no existing mapping exists for this function import
FunctionImportMapping targetFunctionCollision;
if (entityContainerMapping.TryGetFunctionImportMapping(functionImport, out targetFunctionCollision))
{
AddToSchemaErrorWithMessage(Strings.Mapping_FunctionImport_FunctionImportMappedMultipleTimes(functionImportName),
StorageMappingErrorCode.MappingFunctionImportFunctionImportMappedMultipleTimes,
m_sourceLocation, xmlLineInfoNav, m_parsingErrors);
return false;
}
return true;
}
private void ValidateFunctionImportMappingParameters(XPathNavigator nav, EdmFunction targetFunction, EdmFunction functionImport)
{
IXmlLineInfo xmlLineInfoNav = (IXmlLineInfo)nav;
foreach (FunctionParameter targetParameter in targetFunction.Parameters)
{
// find corresponding import parameter
FunctionParameter importParameter;
if (!functionImport.Parameters.TryGetValue(targetParameter.Name, false, out importParameter))
{
AddToSchemaErrorWithMessage(Strings.Mapping_FunctionImport_TargetParameterHasNoCorrespondingImportParameter(targetParameter.Name),
StorageMappingErrorCode.MappingFunctionImportTargetParameterHasNoCorrespondingImportParameter,
m_sourceLocation, xmlLineInfoNav, m_parsingErrors);
}
else
{
// parameters must have the same direction (in|out)
if (targetParameter.Mode != importParameter.Mode)
{
AddToSchemaErrorWithMessage(Strings.Mapping_FunctionImport_IncompatibleParameterMode(targetParameter.Name, targetParameter.Mode, importParameter.Mode),
StorageMappingErrorCode.MappingFunctionImportIncompatibleParameterMode,
m_sourceLocation, xmlLineInfoNav, m_parsingErrors);
}
PrimitiveType importType = Helper.AsPrimitive(importParameter.TypeUsage.EdmType);
Debug.Assert(importType != null, "Function import parameters must be primitive.");
if (Helper.IsSpatialType(importType))
{
importType = Helper.GetSpatialNormalizedPrimitiveType(importType);
}
PrimitiveType cspaceTargetType = (PrimitiveType)StoreItemCollection.StoreProviderManifest.GetEdmType(targetParameter.TypeUsage).EdmType;
if (cspaceTargetType == null)
{
AddToSchemaErrorWithMessage(Strings.Mapping_ProviderReturnsNullType(targetParameter.Name),
StorageMappingErrorCode.MappingStoreProviderReturnsNullEdmType,
m_sourceLocation, xmlLineInfoNav, m_parsingErrors);
return;
}
// there are no type facets declared for function parameter types;
// we simply verify the primitive type kind is equivalent.
// for enums we just use the underlying enum type.
if (cspaceTargetType.PrimitiveTypeKind != importType.PrimitiveTypeKind)
{
var schemaErrorMessage = Helper.IsEnumType(importParameter.TypeUsage.EdmType) ?
Strings.Mapping_FunctionImport_IncompatibleEnumParameterType(
targetParameter.Name,
cspaceTargetType.Name,
importParameter.TypeUsage.EdmType.FullName,
Helper.GetUnderlyingEdmTypeForEnumType(importParameter.TypeUsage.EdmType).Name) :
Strings.Mapping_FunctionImport_IncompatibleParameterType(
targetParameter.Name,
cspaceTargetType.Name,
importType.Name);
AddToSchemaErrorWithMessage(
schemaErrorMessage,
StorageMappingErrorCode.MappingFunctionImportIncompatibleParameterType,
m_sourceLocation, xmlLineInfoNav, m_parsingErrors);
}
}
}
foreach (FunctionParameter importParameter in functionImport.Parameters)
{
// find corresponding target parameter
FunctionParameter targetParameter;
if (!targetFunction.Parameters.TryGetValue(importParameter.Name, false, out targetParameter))
{
AddToSchemaErrorWithMessage(Strings.Mapping_FunctionImport_ImportParameterHasNoCorrespondingTargetParameter(importParameter.Name),
StorageMappingErrorCode.MappingFunctionImportImportParameterHasNoCorrespondingTargetParameter,
m_sourceLocation, xmlLineInfoNav, m_parsingErrors);
}
}
}
private List<FunctionImportStructuralTypeMapping> GetFunctionImportMappingResultMapping(
XPathNavigator nav,
IXmlLineInfo functionImportMappingLineInfo,
EdmFunction targetFunction,
EdmFunction functionImport,
int resultSetIndex,
List<List<FunctionImportStructuralTypeMapping>> typeMappingsList)
{
List<FunctionImportStructuralTypeMapping> typeMappings = new List<FunctionImportStructuralTypeMapping>();
if (nav.MoveToChild(XPathNodeType.Element))
{
do
{
EntitySet entitySet = functionImport.EntitySets.Count > resultSetIndex ?
functionImport.EntitySets[resultSetIndex] : null;
if (nav.LocalName == StorageMslConstructs.EntityTypeMappingElement)
{
EntityType resultEntityType;
if (MetadataHelper.TryGetFunctionImportReturnType<EntityType>(functionImport, resultSetIndex, out resultEntityType))
{
// Cannot specify an entity type mapping for a function import that does not return members of an entity set.
if (entitySet == null)
{
AddToSchemaErrors(Strings.Mapping_FunctionImport_EntityTypeMappingForFunctionNotReturningEntitySet(
StorageMslConstructs.EntityTypeMappingElement, functionImport.Identity),
StorageMappingErrorCode.MappingFunctionImportEntityTypeMappingForFunctionNotReturningEntitySet,
m_sourceLocation, functionImportMappingLineInfo, m_parsingErrors);
}
FunctionImportEntityTypeMapping typeMapping;
if (TryLoadFunctionImportEntityTypeMapping(
nav.Clone(),
resultEntityType,
(EntityType e) => Strings.Mapping_FunctionImport_InvalidContentEntityTypeForEntitySet(e.FullName,
resultEntityType.FullName,
entitySet.Name,
functionImport.Identity),
out typeMapping))
{
typeMappings.Add(typeMapping);
}
}
else
{
AddToSchemaErrors(Strings.Mapping_FunctionImport_ResultMapping_InvalidCTypeETExpected(functionImport.Identity),
StorageMappingErrorCode.MappingFunctionImportUnexpectedEntityTypeMapping,
m_sourceLocation, functionImportMappingLineInfo, m_parsingErrors);
}
}
else if (nav.LocalName == StorageMslConstructs.ComplexTypeMappingElement)
{
ComplexType resultComplexType;
if (MetadataHelper.TryGetFunctionImportReturnType<ComplexType>(functionImport, resultSetIndex, out resultComplexType))
{
Debug.Assert(entitySet == null, "entitySet == null for complex type mapping in function imports.");
FunctionImportComplexTypeMapping typeMapping;
if (TryLoadFunctionImportComplexTypeMapping(nav.Clone(), resultComplexType, functionImport, out typeMapping))
{
typeMappings.Add(typeMapping);
}
}
else
{
AddToSchemaErrors(Strings.Mapping_FunctionImport_ResultMapping_InvalidCTypeCTExpected(functionImport.Identity),
StorageMappingErrorCode.MappingFunctionImportUnexpectedComplexTypeMapping,
m_sourceLocation, functionImportMappingLineInfo, m_parsingErrors);
}
}
}
while (nav.MoveToNext(XPathNodeType.Element));
}
return typeMappings;
}
private bool TryLoadFunctionImportComplexTypeMapping(
XPathNavigator nav,
ComplexType resultComplexType,
EdmFunction functionImport,
out FunctionImportComplexTypeMapping typeMapping)
{
typeMapping = null;
var lineInfo = new LineInfo(nav);
ComplexType complexType;
if (!TryParseComplexTypeAttribute(nav, resultComplexType, functionImport, out complexType))
{
return false;
}
Collection<FunctionImportReturnTypePropertyMapping> columnRenameMappings = new Collection<FunctionImportReturnTypePropertyMapping>();
if (!LoadFunctionImportStructuralType(nav.Clone(), new List<StructuralType>() { complexType }, columnRenameMappings, null))
{
return false;
}
typeMapping = new FunctionImportComplexTypeMapping(complexType, columnRenameMappings, lineInfo);
return true;
}
private bool TryParseComplexTypeAttribute(XPathNavigator nav, ComplexType resultComplexType, EdmFunction functionImport, out ComplexType complexType)
{
IXmlLineInfo xmlLineInfoNav = (IXmlLineInfo)nav;
string complexTypeName = GetAttributeValue(nav.Clone(), StorageMslConstructs.ComplexTypeMappingTypeNameAttribute);
complexTypeName = GetAliasResolvedValue(complexTypeName);
if (!this.EdmItemCollection.TryGetItem<ComplexType>(complexTypeName, out complexType))
{
AddToSchemaErrorsWithMemberInfo(Strings.Mapping_InvalidContent_Complex_Type, complexTypeName,
StorageMappingErrorCode.InvalidComplexType, m_sourceLocation, xmlLineInfoNav, m_parsingErrors);
return false;
}
if (!Helper.IsAssignableFrom(resultComplexType, complexType))
{
IXmlLineInfo lineInfo = xmlLineInfoNav;
AddToSchemaErrorWithMessage(
Strings.Mapping_FunctionImport_ResultMapping_MappedTypeDoesNotMatchReturnType(functionImport.Identity, complexType.FullName),
StorageMappingErrorCode.InvalidComplexType, m_sourceLocation, xmlLineInfoNav, m_parsingErrors);
return false;
}
return true;
}
private bool TryLoadFunctionImportEntityTypeMapping(
XPathNavigator nav,
EntityType resultEntityType,
Func<EntityType, string> registerEntityTypeMismatchError,
out FunctionImportEntityTypeMapping typeMapping)
{
typeMapping = null;
var lineInfo = new LineInfo(nav);
// Process entity type.
string entityTypeString = GetAttributeValue(nav.Clone(), StorageMslConstructs.EntitySetMappingTypeNameAttribute);
Set<EntityType> isOfTypeEntityTypes;
Set<EntityType> entityTypes;
{
// Verify the entity type is appropriate to the function import's result entity type.
if (!TryParseEntityTypeAttribute(nav.Clone(), resultEntityType, registerEntityTypeMismatchError, out isOfTypeEntityTypes, out entityTypes))
{
return false;
}
}
IEnumerable<StructuralType> currentTypesInHierachy = isOfTypeEntityTypes.Concat(entityTypes).Distinct().OfType<StructuralType>();
Collection<FunctionImportReturnTypePropertyMapping> columnRenameMappings = new Collection<FunctionImportReturnTypePropertyMapping>();
// Process all conditions and column renames.
List<FunctionImportEntityTypeMappingCondition> conditions = new List<FunctionImportEntityTypeMappingCondition>();
if (!LoadFunctionImportStructuralType(nav.Clone(), currentTypesInHierachy, columnRenameMappings, conditions))
{
return false;
}
typeMapping = new FunctionImportEntityTypeMapping(isOfTypeEntityTypes, entityTypes, conditions, columnRenameMappings, lineInfo);
return true;
}
private bool LoadFunctionImportStructuralType(
XPathNavigator nav,
IEnumerable<StructuralType> currentTypes,
Collection<FunctionImportReturnTypePropertyMapping> columnRenameMappings,
List<FunctionImportEntityTypeMappingCondition> conditions)
{
Debug.Assert(null != columnRenameMappings, "columnRenameMappings cannot be null");
Debug.Assert(null != nav, "nav cannot be null");
Debug.Assert(null != currentTypes, "currentTypes cannot be null");
IXmlLineInfo lineInfo = (IXmlLineInfo)(nav.Clone());
if (nav.MoveToChild(XPathNodeType.Element))
{
do
{
if (nav.LocalName == StorageMslConstructs.ScalarPropertyElement)
{
LoadFunctionImportStructuralTypeMappingScalarProperty(nav, columnRenameMappings, currentTypes);
}
if (nav.LocalName == StorageMslConstructs.ConditionElement)
{
LoadFunctionImportEntityTypeMappingCondition(nav, conditions);
}
}
while (nav.MoveToNext(XPathNodeType.Element));
}
bool errorFound = false;
if (null != conditions)
{
// make sure a single condition is specified per column
HashSet<string> columnsWithConditions = new HashSet<string>();
foreach (var condition in conditions)
{
if (!columnsWithConditions.Add(condition.ColumnName))
{
AddToSchemaErrorWithMessage(
Strings.Mapping_InvalidContent_Duplicate_Condition_Member(condition.ColumnName),
StorageMappingErrorCode.ConditionError,
m_sourceLocation, lineInfo, m_parsingErrors);
errorFound = true;
}
}
}
return !errorFound;
}
private void LoadFunctionImportStructuralTypeMappingScalarProperty(
XPathNavigator nav,
Collection<FunctionImportReturnTypePropertyMapping> columnRenameMappings,
IEnumerable<StructuralType> currentTypes)
{
var lineInfo = new LineInfo(nav);
string memberName = GetAliasResolvedAttributeValue(nav.Clone(), StorageMslConstructs.ScalarPropertyNameAttribute);
string columnName = GetAliasResolvedAttributeValue(nav.Clone(), StorageMslConstructs.ScalarPropertyColumnNameAttribute);
// Negative case: the property name is invalid
if (!currentTypes.All(t=>t.Members.Contains(memberName)))
{
AddToSchemaErrorWithMessage(
Strings.Mapping_InvalidContent_Cdm_Member(memberName),
StorageMappingErrorCode.InvalidEdmMember,
m_sourceLocation, lineInfo, m_parsingErrors);
}
if (columnRenameMappings.Any(m => m.CMember == memberName))
{
// Negative case: duplicate member name mapping in one type rename mapping
AddToSchemaErrorWithMessage(
Strings.Mapping_InvalidContent_Duplicate_Cdm_Member(memberName),
StorageMappingErrorCode.DuplicateMemberMapping,
m_sourceLocation, lineInfo, m_parsingErrors);
}
else
{
columnRenameMappings.Add(new FunctionImportReturnTypeScalarPropertyMapping(memberName, columnName, lineInfo));
}
}
private bool TryCreateFunctionImportMappingComposableWithStructuralResult(
EdmFunction functionImport,
EdmFunction cTypeTargetFunction,
List<FunctionImportStructuralTypeMapping> typeMappings,
StructuralType structuralResultType,
RowType cTypeTvfElementType,
RowType sTypeTvfElementType,
IXmlLineInfo lineInfo,
out FunctionImportMappingComposable mapping)
{
mapping = null;
// If it is an implicit structural type mapping, add a type mapping fragment for the return type of the function import,
// unless it is an abstract type.
if (typeMappings.Count == 0)
{
StructuralType resultType;
if (MetadataHelper.TryGetFunctionImportReturnType<StructuralType>(functionImport, 0, out resultType))
{
if (resultType.Abstract)
{
AddToSchemaErrorWithMemberAndStructure(Strings.Mapping_FunctionImport_ImplicitMappingForAbstractReturnType,
resultType.FullName, functionImport.Identity,
StorageMappingErrorCode.MappingOfAbstractType, m_sourceLocation, lineInfo, m_parsingErrors);
return false;
}
if (resultType.BuiltInTypeKind == BuiltInTypeKind.EntityType)
{
typeMappings.Add(new FunctionImportEntityTypeMapping(
Enumerable.Empty<EntityType>(),
new EntityType[] { (EntityType)resultType },
Enumerable.Empty<FunctionImportEntityTypeMappingCondition>(),
new Collection<FunctionImportReturnTypePropertyMapping>(),
new LineInfo(lineInfo)));
}
else
{
Debug.Assert(resultType.BuiltInTypeKind == BuiltInTypeKind.ComplexType, "resultType.BuiltInTypeKind == BuiltInTypeKind.ComplexType");
typeMappings.Add(new FunctionImportComplexTypeMapping(
(ComplexType)resultType,
new Collection<FunctionImportReturnTypePropertyMapping>(),
new LineInfo(lineInfo)));
}
}
}
// Validate and convert FunctionImportEntityTypeMapping elements into structure suitable for composable function import mapping.
var functionImportKB = new FunctionImportStructuralTypeMappingKB(typeMappings, this.EdmItemCollection);
var structuralTypeMappings = new List<Tuple<StructuralType, List<StorageConditionPropertyMapping>, List<StoragePropertyMapping>>>();
EdmProperty[] targetFunctionKeys = null;
if (functionImportKB.MappedEntityTypes.Count > 0)
{
// Validate TPH ambiguity.
if (!functionImportKB.ValidateTypeConditions(/*validateAmbiguity: */true, m_parsingErrors, m_sourceLocation))
{
return false;
}
// For each mapped entity type, prepare list of conditions and list of property mappings.
for (int i = 0; i < functionImportKB.MappedEntityTypes.Count; ++i)
{
List<StorageConditionPropertyMapping> typeConditions;
List<StoragePropertyMapping> propertyMappings;
if (TryConvertToEntityTypeConditionsAndPropertyMappings(
functionImport,
functionImportKB,
i,
cTypeTvfElementType,
sTypeTvfElementType,
lineInfo, out typeConditions, out propertyMappings))
{
structuralTypeMappings.Add(Tuple.Create((StructuralType)functionImportKB.MappedEntityTypes[i], typeConditions, propertyMappings));
}
}
if (structuralTypeMappings.Count < functionImportKB.MappedEntityTypes.Count)
{
// Some of the entity types produced errors during conversion, exit.
return false;
}
// Infer target function keys based on the c-space entity types.
if (!TryInferTVFKeys(structuralTypeMappings, out targetFunctionKeys))
{
AddToSchemaErrorsWithMemberInfo(Strings.Mapping_FunctionImport_CannotInferTargetFunctionKeys, functionImport.Identity,
StorageMappingErrorCode.MappingFunctionImportCannotInferTargetFunctionKeys, m_sourceLocation, lineInfo, m_parsingErrors);
return false;
}
}
else
{
ComplexType resultComplexType;
if (MetadataHelper.TryGetFunctionImportReturnType<ComplexType>(functionImport, 0, out resultComplexType))
{
// Gather and validate complex type property mappings.
List<StoragePropertyMapping> propertyMappings;
if (!TryConvertToProperyMappings(resultComplexType, cTypeTvfElementType, sTypeTvfElementType, functionImport, functionImportKB, lineInfo, out propertyMappings))
{
return false;
}
structuralTypeMappings.Add(Tuple.Create((StructuralType)resultComplexType, new List<StorageConditionPropertyMapping>(), propertyMappings));
}
else
{
Debug.Fail("Function import return type is expected to be a collection of complex type.");
}
}
mapping = new FunctionImportMappingComposable(
functionImport,
cTypeTargetFunction,
structuralTypeMappings,
targetFunctionKeys,
m_storageMappingItemCollection,
m_sourceLocation,
new LineInfo(lineInfo));
return true;
}
/// <summary>
/// Attempts to infer key columns of the target function based on the function import mapping.
/// </summary>
internal static bool TryInferTVFKeys(List<Tuple<StructuralType, List<StorageConditionPropertyMapping>, List<StoragePropertyMapping>>> structuralTypeMappings, out EdmProperty[] keys)
{
keys = null;
Debug.Assert(structuralTypeMappings.Count > 0, "Function import returning entities must have non-empty structuralTypeMappings.");
foreach (var typeMapping in structuralTypeMappings)
{
EdmProperty[] currentKeys;
if (!TryInferTVFKeysForEntityType((EntityType)typeMapping.Item1, typeMapping.Item3, out currentKeys))
{
keys = null;
return false;
}
if (keys == null)
{
keys = currentKeys;
}
else
{
// Make sure all keys are mapped to the same columns.
Debug.Assert(keys.Length == currentKeys.Length, "All subtypes must have the same number of keys.");
for (int i = 0; i < keys.Length; ++i)
{
if (!keys[i].EdmEquals(currentKeys[i]))
{
keys = null;
return false;
}
}
}
}
// Make sure columns are non-nullable, otherwise it shouldn't be considered a key.
for (int i = 0; i < keys.Length; ++i)
{
if (keys[i].Nullable)
{
keys = null;
return false;
}
}
return true;
}
private static bool TryInferTVFKeysForEntityType(EntityType entityType, List<StoragePropertyMapping> propertyMappings, out EdmProperty[] keys)
{
keys = new EdmProperty[entityType.KeyMembers.Count];
for (int i = 0; i < keys.Length; ++i)
{
var mapping = propertyMappings[entityType.Properties.IndexOf((EdmProperty)entityType.KeyMembers[i])] as StorageScalarPropertyMapping;
if (mapping == null)
{
keys = null;
return false;
}
keys[i] = mapping.ColumnProperty;
}
return true;
}
private bool TryCreateFunctionImportMappingComposableWithScalarResult(
EdmFunction functionImport,
EdmFunction cTypeTargetFunction,
EdmFunction sTypeTargetFunction,
EdmType scalarResultType,
RowType cTypeTvfElementType,
RowType sTypeTvfElementType,
IXmlLineInfo lineInfo,
out FunctionImportMappingComposable mapping)
{
mapping = null;
// Make sure that TVF returns exactly one column
if (cTypeTvfElementType.Properties.Count > 1)
{
AddToSchemaErrors(Strings.Mapping_FunctionImport_ScalarMappingToMulticolumnTVF(functionImport.Identity, sTypeTargetFunction.Identity),
StorageMappingErrorCode.MappingFunctionImportScalarMappingToMulticolumnTVF, m_sourceLocation, lineInfo, m_parsingErrors);
return false;
}
// Make sure that scalarResultType agrees with the column type.
if (!ValidateFunctionImportMappingResultTypeCompatibility(TypeUsage.Create(scalarResultType), cTypeTvfElementType.Properties[0].TypeUsage))
{
AddToSchemaErrors(Strings.Mapping_FunctionImport_ScalarMappingTypeMismatch(
functionImport.ReturnParameter.TypeUsage.EdmType.FullName,
functionImport.Identity,
sTypeTargetFunction.ReturnParameter.TypeUsage.EdmType.FullName,
sTypeTargetFunction.Identity),
StorageMappingErrorCode.MappingFunctionImportScalarMappingTypeMismatch, m_sourceLocation, lineInfo, m_parsingErrors);
return false;
}
mapping = new FunctionImportMappingComposable(
functionImport,
cTypeTargetFunction,
null,
null,
m_storageMappingItemCollection,
m_sourceLocation,
new LineInfo(lineInfo));
return true;
}
private bool ValidateFunctionImportMappingResultTypeCompatibility(TypeUsage cSpaceMemberType, TypeUsage sSpaceMemberType)
{
// Function result data flows from S-side to C-side.
var fromType = sSpaceMemberType;
var toType = ResolveTypeUsageForEnums(cSpaceMemberType);
bool directlyPromotable = TypeSemantics.IsStructurallyEqualOrPromotableTo(fromType, toType);
bool inverselyPromotable = TypeSemantics.IsStructurallyEqualOrPromotableTo(toType, fromType);
// We are quite lax here. We only require that values belong to the same class (can flow in one or the other direction).
// We could require precisely s-type to be promotable to c-type, but in this case it won't be possible to reuse the same
// c-types for mapped functions and entity sets, because entity sets (read-write) require c-types to be promotable to s-types.
return directlyPromotable || inverselyPromotable;
}
private void LoadFunctionImportEntityTypeMappingCondition(XPathNavigator nav, List<FunctionImportEntityTypeMappingCondition> conditions)
{
var lineInfo = new LineInfo(nav);
string columnName = GetAliasResolvedAttributeValue(nav.Clone(), StorageMslConstructs.ConditionColumnNameAttribute);
string value = GetAliasResolvedAttributeValue(nav.Clone(), StorageMslConstructs.ConditionValueAttribute);
string isNull = GetAliasResolvedAttributeValue(nav.Clone(), StorageMslConstructs.ConditionIsNullAttribute);
//Either Value or NotNull need to be specifid on the condition mapping but not both
if ((isNull != null) && (value != null))
{
AddToSchemaErrors(Strings.Mapping_InvalidContent_ConditionMapping_Both_Values,
StorageMappingErrorCode.ConditionError, m_sourceLocation, lineInfo, m_parsingErrors);
}
else if ((isNull == null) && (value == null))
{
AddToSchemaErrors(Strings.Mapping_InvalidContent_ConditionMapping_Either_Values,
StorageMappingErrorCode.ConditionError, m_sourceLocation, lineInfo, m_parsingErrors);
}
else
{
if (isNull != null)
{
bool isNullValue = Convert.ToBoolean(isNull, CultureInfo.InvariantCulture);
conditions.Add(new FunctionImportEntityTypeMappingConditionIsNull(columnName, isNullValue, lineInfo));
}
else
{
XPathNavigator columnValue = nav.Clone();
columnValue.MoveToAttribute(StorageMslConstructs.ConditionValueAttribute, string.Empty);
conditions.Add(new FunctionImportEntityTypeMappingConditionValue(columnName, columnValue, lineInfo));
}
}
}
private bool TryConvertToEntityTypeConditionsAndPropertyMappings(
EdmFunction functionImport,
FunctionImportStructuralTypeMappingKB functionImportKB,
int typeID,
RowType cTypeTvfElementType,
RowType sTypeTvfElementType,
IXmlLineInfo navLineInfo,
out List<StorageConditionPropertyMapping> typeConditions,
out List<StoragePropertyMapping> propertyMappings)
{
var entityType = functionImportKB.MappedEntityTypes[typeID];
typeConditions = new List<StorageConditionPropertyMapping>();
bool errorFound = false;
// Gather and validate entity type conditions from the type-producing fragments.
foreach (var entityTypeMapping in functionImportKB.NormalizedEntityTypeMappings.Where(f => f.ImpliedEntityTypes[typeID]))
{
foreach (var condition in entityTypeMapping.ColumnConditions.Where(c => c != null))
{
EdmProperty column;
if (sTypeTvfElementType.Properties.TryGetValue(condition.ColumnName, false, out column))
{
object value;
bool? isNull;
if (condition.ConditionValue.IsSentinel)
{
value = null;
if (condition.ConditionValue == ValueCondition.IsNull)
{
isNull = true;
}
else
{
Debug.Assert(condition.ConditionValue == ValueCondition.IsNotNull, "Only IsNull or IsNotNull condition values are expected.");
isNull = false;
}
}
else
{
var cTypeColumn = cTypeTvfElementType.Properties[column.Name];
Debug.Assert(cTypeColumn != null, "cTypeColumn != null");
Debug.Assert(Helper.IsPrimitiveType(cTypeColumn.TypeUsage.EdmType), "S-space columns are expected to be of a primitive type.");
var cPrimitiveType = (PrimitiveType)cTypeColumn.TypeUsage.EdmType;
Debug.Assert(cPrimitiveType.ClrEquivalentType != null, "Scalar Types should have associated clr type");
Debug.Assert(condition is FunctionImportEntityTypeMappingConditionValue, "Non-sentinel condition is expected to be of type FunctionImportEntityTypeMappingConditionValue.");
value = ((FunctionImportEntityTypeMappingConditionValue)condition).GetConditionValue(
cPrimitiveType.ClrEquivalentType,
handleTypeNotComparable: () =>
{
AddToSchemaErrorWithMemberAndStructure(
Strings.Mapping_InvalidContent_ConditionMapping_InvalidPrimitiveTypeKind, column.Name, column.TypeUsage.EdmType.FullName,
StorageMappingErrorCode.ConditionError,
m_sourceLocation, condition.LineInfo, m_parsingErrors);
},
handleInvalidConditionValue: () =>
{
AddToSchemaErrors(
Strings.Mapping_ConditionValueTypeMismatch,
StorageMappingErrorCode.ConditionError,
m_sourceLocation, condition.LineInfo, m_parsingErrors);
});
if (value == null)
{
errorFound = true;
continue;
}
isNull = null;
}
typeConditions.Add(new StorageConditionPropertyMapping(null, column, value, isNull));
}
else
{
AddToSchemaErrorsWithMemberInfo(
Strings.Mapping_InvalidContent_Column, condition.ColumnName,
StorageMappingErrorCode.InvalidStorageMember,
m_sourceLocation, condition.LineInfo, m_parsingErrors);
}
}
}
// Gather and validate entity type property mappings.
errorFound |= !TryConvertToProperyMappings(entityType, cTypeTvfElementType, sTypeTvfElementType, functionImport, functionImportKB, navLineInfo, out propertyMappings);
return !errorFound;
}
private bool TryConvertToProperyMappings(
StructuralType structuralType,
RowType cTypeTvfElementType,
RowType sTypeTvfElementType,
EdmFunction functionImport,
FunctionImportStructuralTypeMappingKB functionImportKB,
IXmlLineInfo navLineInfo,
out List<StoragePropertyMapping> propertyMappings)
{
propertyMappings = new List<StoragePropertyMapping>();
// Gather and validate structuralType property mappings.
bool errorFound = false;
foreach (EdmProperty property in Common.TypeHelpers.GetAllStructuralMembers(structuralType))
{
// Only scalar property mappings are supported at the moment.
if (!Helper.IsScalarType(property.TypeUsage.EdmType))
{
EdmSchemaError error = new EdmSchemaError(
Strings.Mapping_Invalid_CSide_ScalarProperty(property.Name),
(int)StorageMappingErrorCode.InvalidTypeInScalarProperty,
EdmSchemaErrorSeverity.Error,
m_sourceLocation, navLineInfo.LineNumber, navLineInfo.LinePosition);
m_parsingErrors.Add(error);
errorFound = true;
continue;
}
string columnName = null;
IXmlLineInfo columnMappingLineInfo = null;
FunctionImportReturnTypeStructuralTypeColumnRenameMapping columnRenameMapping;
bool explicitPropertyMapping;
if (functionImportKB.ReturnTypeColumnsRenameMapping.TryGetValue(property.Name, out columnRenameMapping))
{
explicitPropertyMapping = true;
columnName = columnRenameMapping.GetRename(structuralType, out columnMappingLineInfo);
}
else
{
explicitPropertyMapping = false;
columnName = property.Name;
}
columnMappingLineInfo = columnMappingLineInfo != null && columnMappingLineInfo.HasLineInfo() ? columnMappingLineInfo : navLineInfo;
EdmProperty column;
if (sTypeTvfElementType.Properties.TryGetValue(columnName, false, out column))
{
Debug.Assert(cTypeTvfElementType.Properties.Contains(columnName), "cTypeTvfElementType.Properties.Contains(columnName)");
var cTypeColumn = cTypeTvfElementType.Properties[columnName];
if (ValidateFunctionImportMappingResultTypeCompatibility(property.TypeUsage, cTypeColumn.TypeUsage))
{
propertyMappings.Add(new StorageScalarPropertyMapping(property, column));
}
else
{
EdmSchemaError error = new EdmSchemaError(
GetInvalidMemberMappingErrorMessage(property, column),
(int)StorageMappingErrorCode.IncompatibleMemberMapping,
EdmSchemaErrorSeverity.Error,
m_sourceLocation, columnMappingLineInfo.LineNumber, columnMappingLineInfo.LinePosition);
m_parsingErrors.Add(error);
}
}
else
{
if (explicitPropertyMapping)
{
AddToSchemaErrorsWithMemberInfo(
Strings.Mapping_InvalidContent_Column, columnName,
StorageMappingErrorCode.InvalidStorageMember,
m_sourceLocation, columnMappingLineInfo, m_parsingErrors);
}
else
{
var error = new EdmSchemaError(
Strings.Mapping_FunctionImport_PropertyNotMapped(property.Name, structuralType.FullName, functionImport.Identity),
(int)StorageMappingErrorCode.MappingFunctionImportReturnTypePropertyNotMapped,
EdmSchemaErrorSeverity.Error,
m_sourceLocation, columnMappingLineInfo.LineNumber, columnMappingLineInfo.LinePosition);
m_parsingErrors.Add(error);
errorFound = true;
}
}
}
// Make sure that propertyMappings is in the order of properties of the structuredType.
// The rest of the code depends on it.
Debug.Assert(errorFound ||
Common.TypeHelpers.GetAllStructuralMembers(structuralType).Count == propertyMappings.Count &&
Common.TypeHelpers.GetAllStructuralMembers(structuralType).Cast<EdmMember>().Zip(propertyMappings)
.All(ppm => ppm.Key.EdmEquals(ppm.Value.EdmProperty)), "propertyMappings order does not correspond to the order of properties in the structuredType.");
return !errorFound;
}
#endregion
/// <summary>
/// The method loads the child nodes for the AssociationType Mapping node
/// into the internal datastructures.
/// </summary>
/// <param name="nav"></param>
/// <param name="associationSetMapping"></param>
/// <param name="associationTypeName"></param>
/// <param name="tableName"></param>
/// <param name="storageEntityContainerType"></param>
private void LoadAssociationTypeMapping(XPathNavigator nav, StorageAssociationSetMapping associationSetMapping, string associationTypeName, string tableName, EntityContainer storageEntityContainerType)
{
IXmlLineInfo navLineInfo = (IXmlLineInfo)nav;
//Get the association type for association type name specified in MSL
//If no AssociationType with the given name exists, add a schema error and return
AssociationType associationType;
this.EdmItemCollection.TryGetItem<AssociationType>(associationTypeName, out associationType);
if (associationType == null)
{
//There is no point in continuing loading if the AssociationType is null
AddToSchemaErrorsWithMemberInfo(Strings.Mapping_InvalidContent_Association_Type, associationTypeName,
StorageMappingErrorCode.InvalidAssociationType, m_sourceLocation, navLineInfo, m_parsingErrors);
return;
}
//Verify that AssociationType specified should be the declared type of
//AssociationSet or a derived Type of it.
//Future Enhancement : Change the code to use EdmEquals
if ((!(associationSetMapping.Set.ElementType.Equals(associationType))))
{
AddToSchemaErrorWithMessage(Strings.Mapping_Invalid_Association_Type_For_Association_Set(associationTypeName,
associationSetMapping.Set.ElementType.FullName, associationSetMapping.Set.Name),
StorageMappingErrorCode.DuplicateTypeMapping, m_sourceLocation, navLineInfo, m_parsingErrors);
return;
}
//Create an AssociationTypeMapping to hold the information for AssociationType mapping.
StorageAssociationTypeMapping associationTypeMapping = new StorageAssociationTypeMapping(associationType, associationSetMapping);
associationSetMapping.AddTypeMapping(associationTypeMapping);
//If the table name was not specified on the AssociationSetMapping element
//Then there should have been a query view. Otherwise throw.
if (String.IsNullOrEmpty(tableName) && (associationSetMapping.QueryView == null))
{
AddToSchemaErrors(Strings.Mapping_InvalidContent_Table_Expected, StorageMappingErrorCode.InvalidTable,
m_sourceLocation, navLineInfo, m_parsingErrors);
}
else
{
StorageMappingFragment fragment = LoadAssociationMappingFragment(nav.Clone(), associationSetMapping, associationTypeMapping, tableName, storageEntityContainerType);
if (fragment != null)
{
//Fragment can be null because of validation errors
associationTypeMapping.AddFragment(fragment);
}
}
}
/// <summary>
/// Loads function mappings for the entity type.
/// </summary>
/// <param name="associationSetMapping"></param>
/// <param name="associationTypeMapping"></param>
/// <param name="nav"></param>
private void LoadAssociationTypeModificationFunctionMapping(
XPathNavigator nav,
StorageAssociationSetMapping associationSetMapping,
StorageAssociationTypeMapping associationTypeMapping)
{
// create function loader
ModificationFunctionMappingLoader functionLoader = new ModificationFunctionMappingLoader(this, associationSetMapping.Set);
// Load all function definitions (for insert, delete and update)
StorageModificationFunctionMapping deleteFunctionMapping = null;
StorageModificationFunctionMapping insertFunctionMapping = null;
if (nav.MoveToChild(XPathNodeType.Element))
{
do
{
switch (nav.LocalName)
{
case StorageMslConstructs.DeleteFunctionElement:
deleteFunctionMapping = functionLoader.LoadAssociationSetModificationFunctionMapping(nav.Clone(), associationSetMapping.Set, false);
break;
case StorageMslConstructs.InsertFunctionElement:
insertFunctionMapping = functionLoader.LoadAssociationSetModificationFunctionMapping(nav.Clone(), associationSetMapping.Set, true);
break;
}
} while (nav.MoveToNext(XPathNodeType.Element));
}
// register function mapping information
associationSetMapping.ModificationFunctionMapping = new StorageAssociationSetModificationFunctionMapping(
(AssociationSet)associationSetMapping.Set, deleteFunctionMapping, insertFunctionMapping);
}
/// <summary>
/// The method loads the child nodes for the TableMappingFragment under the EntityType node
/// into the internal datastructures.
/// </summary>
private StorageMappingFragment LoadMappingFragment(
XPathNavigator nav,
StorageEntityTypeMapping typeMapping,
string tableName,
EntityContainer storageEntityContainerType,
bool distinctFlag)
{
IXmlLineInfo navLineInfo = (IXmlLineInfo)nav;
//First make sure that there was no QueryView specified for this Set
if (typeMapping.SetMapping.QueryView != null)
{
AddToSchemaErrorsWithMemberInfo(Strings.Mapping_QueryView_PropertyMaps, typeMapping.SetMapping.Set.Name,
StorageMappingErrorCode.PropertyMapsWithQueryView, m_sourceLocation, navLineInfo, m_parsingErrors);
return null;
}
//Get the table type that represents this table
EntitySet tableMember;
storageEntityContainerType.TryGetEntitySetByName(tableName, false /*ignoreCase*/, out tableMember);
if (tableMember == null)
{
//There is no point in continuing loading if the Table on S side can not be found
AddToSchemaErrorsWithMemberInfo(Strings.Mapping_InvalidContent_Table, tableName,
StorageMappingErrorCode.InvalidTable, m_sourceLocation, navLineInfo, m_parsingErrors);
return null;
}
EntityType tableType = tableMember.ElementType;
//Create a table mapping fragment to hold the mapping information for a TableMappingFragment node
StorageMappingFragment fragment = new StorageMappingFragment(tableMember, typeMapping, distinctFlag);
//Set the Start Line Information on Fragment
fragment.StartLineNumber = navLineInfo.LineNumber;
fragment.StartLinePosition = navLineInfo.LinePosition;
//Go through the property mappings for this TableMappingFragment and load them in memory.
if (nav.MoveToChild(XPathNodeType.Element))
{
do
{
//need to get the type that this member exists in
EdmType containerType = null;
string propertyName = StorageMappingItemLoader.GetAttributeValue(nav.Clone(), StorageMslConstructs.ComplexPropertyNameAttribute);
//PropertyName could be null for Condition Maps
if (propertyName != null)
{
containerType = typeMapping.GetContainerType(propertyName);
}
switch (nav.LocalName)
{
case StorageMslConstructs.ScalarPropertyElement:
StorageScalarPropertyMapping scalarMap = LoadScalarPropertyMapping(nav.Clone(), containerType, tableType.Properties);
if (scalarMap != null)
{
//scalarMap can be null in invalid cases
fragment.AddProperty(scalarMap);
}
break;
case StorageMslConstructs.ComplexPropertyElement:
StorageComplexPropertyMapping complexMap =
LoadComplexPropertyMapping(nav.Clone(), containerType, tableType.Properties);
//Complex Map can be null in case of invalid MSL files.
if (complexMap != null)
{
fragment.AddProperty(complexMap);
}
break;
case StorageMslConstructs.ConditionElement:
StorageConditionPropertyMapping conditionMap =
LoadConditionPropertyMapping(nav.Clone(), containerType, tableType.Properties);
//conditionMap can be null in cases of invalid Map
if (conditionMap != null)
{
fragment.AddConditionProperty(conditionMap, duplicateMemberConditionError: (member) =>
{
AddToSchemaErrorsWithMemberInfo(
Strings.Mapping_InvalidContent_Duplicate_Condition_Member, member.Name,
StorageMappingErrorCode.ConditionError,
m_sourceLocation, navLineInfo, m_parsingErrors);
});
}
break;
default:
AddToSchemaErrors(Strings.Mapping_InvalidContent_General,
StorageMappingErrorCode.InvalidContent, m_sourceLocation, navLineInfo, m_parsingErrors);
break;
}
} while (nav.MoveToNext(XPathNodeType.Element));
}
nav.MoveToChild(XPathNodeType.Element);
return fragment;
}
/// <summary>
/// The method loads the child nodes for the TableMappingFragment under the AssociationType node
/// into the internal datastructures.
/// </summary>
/// <param name="nav"></param>
/// <param name="typeMapping"></param>
/// <param name="setMapping"></param>
/// <param name="tableName"></param>
/// <param name="storageEntityContainerType"></param>
/// <returns></returns>
private StorageMappingFragment LoadAssociationMappingFragment(XPathNavigator nav, StorageAssociationSetMapping setMapping, StorageAssociationTypeMapping typeMapping, string tableName, EntityContainer storageEntityContainerType)
{
IXmlLineInfo navLineInfo = (IXmlLineInfo)nav;
StorageMappingFragment fragment = null;
EntityType tableType = null;
//If there is a query view, Dont create a mapping fragment since there should n't be one
if (setMapping.QueryView == null)
{
//Get the table type that represents this table
EntitySet tableMember;
storageEntityContainerType.TryGetEntitySetByName(tableName, false /*ignoreCase*/, out tableMember);
if (tableMember == null)
{
//There is no point in continuing loading if the Table is null
AddToSchemaErrorsWithMemberInfo(Strings.Mapping_InvalidContent_Table, tableName,
StorageMappingErrorCode.InvalidTable, m_sourceLocation, navLineInfo, m_parsingErrors);
return null;
}
tableType = tableMember.ElementType;
//Create a Mapping fragment and load all the End node under it
fragment = new StorageMappingFragment(tableMember, typeMapping, false /*No distinct flag*/);
//Set the Start Line Information on Fragment, For AssociationSet there are
//no fragments, so the start Line Info is same as that of Set
fragment.StartLineNumber = setMapping.StartLineNumber;
fragment.StartLinePosition = setMapping.StartLinePosition;
}
do
{
//need to get the type that this member exists in
switch (nav.LocalName)
{
case StorageMslConstructs.EndPropertyMappingElement:
//Make sure that there was no QueryView specified for this Set
if (setMapping.QueryView != null)
{
AddToSchemaErrorsWithMemberInfo(Strings.Mapping_QueryView_PropertyMaps, setMapping.Set.Name,
StorageMappingErrorCode.PropertyMapsWithQueryView, m_sourceLocation, navLineInfo, m_parsingErrors);
return null;
}
string endName = GetAliasResolvedAttributeValue(nav.Clone(), StorageMslConstructs.EndPropertyMappingNameAttribute);
EdmMember endMember = null;
typeMapping.AssociationType.Members.TryGetValue(endName, false, out endMember);
AssociationEndMember end = endMember as AssociationEndMember;
if (end == null)
{
//Don't try to load the end property map if the end property itself is null
AddToSchemaErrorsWithMemberInfo(Strings.Mapping_InvalidContent_End, endName,
StorageMappingErrorCode.InvalidEdmMember, m_sourceLocation, navLineInfo, m_parsingErrors);
continue;
}
fragment.AddProperty((LoadEndPropertyMapping(nav.Clone(), end, tableType)));
break;
case StorageMslConstructs.ConditionElement:
//Make sure that there was no QueryView specified for this Set
if (setMapping.QueryView != null)
{
AddToSchemaErrorsWithMemberInfo(Strings.Mapping_QueryView_PropertyMaps, setMapping.Set.Name,
StorageMappingErrorCode.PropertyMapsWithQueryView, m_sourceLocation, navLineInfo, m_parsingErrors);
return null;
}
//Need to add validation for conditions in Association mapping fragment.
StorageConditionPropertyMapping conditionMap = LoadConditionPropertyMapping(nav.Clone(), null /*containerType*/, tableType.Properties);
//conditionMap can be null in cases of invalid Map
if (conditionMap != null)
{
fragment.AddConditionProperty(conditionMap, duplicateMemberConditionError: (member) =>
{
AddToSchemaErrorsWithMemberInfo(
Strings.Mapping_InvalidContent_Duplicate_Condition_Member, member.Name,
StorageMappingErrorCode.ConditionError,
m_sourceLocation, navLineInfo, m_parsingErrors);
});
}
break;
case StorageMslConstructs.ModificationFunctionMappingElement:
setMapping.HasModificationFunctionMapping = true;
LoadAssociationTypeModificationFunctionMapping(nav.Clone(), setMapping, typeMapping);
break;
default:
AddToSchemaErrors(Strings.Mapping_InvalidContent_General,
StorageMappingErrorCode.InvalidContent, m_sourceLocation, navLineInfo, m_parsingErrors);
break;
}
} while (nav.MoveToNext(XPathNodeType.Element));
return fragment;
}
/// <summary>
/// The method loads the ScalarProperty mapping
/// into the internal datastructures.
/// </summary>
/// <param name="nav"></param>
/// <param name="containerType"></param>
/// <param name="tableType"></param>
/// <returns></returns>
private StorageScalarPropertyMapping LoadScalarPropertyMapping(XPathNavigator nav, EdmType containerType, ReadOnlyMetadataCollection<EdmProperty> tableProperties)
{
IXmlLineInfo xmlLineInfoNav = (IXmlLineInfo)nav;
//Get the property name from MSL.
string propertyName = GetAliasResolvedAttributeValue(nav.Clone(), StorageMslConstructs.ScalarPropertyNameAttribute);
EdmProperty member = null;
if (!String.IsNullOrEmpty(propertyName))
{
//If the container type is a collection type, there wouldn't be a member to represent this scalar property
if (containerType == null || !(Helper.IsCollectionType(containerType)))
{
//If container type is null that means we have not found the member in any of the IsOfTypes.
if (containerType != null)
{
if (Helper.IsRefType(containerType))
{
RefType refType = (RefType)containerType;
((EntityType)refType.ElementType).Properties.TryGetValue(propertyName, false /*ignoreCase*/, out member);
}
else
{
EdmMember tempMember;
(containerType as StructuralType).Members.TryGetValue(propertyName, false, out tempMember);
member = tempMember as EdmProperty;
}
}
if (member == null)
{
AddToSchemaErrorsWithMemberInfo(Strings.Mapping_InvalidContent_Cdm_Member, propertyName,
StorageMappingErrorCode.InvalidEdmMember, m_sourceLocation, xmlLineInfoNav, m_parsingErrors);
}
}
}
//Get the property from Storeside
string columnName = GetAliasResolvedAttributeValue(nav.Clone(), StorageMslConstructs.ScalarPropertyColumnNameAttribute);
Debug.Assert(columnName != null, "XSD validation should have caught this");
EdmProperty columnMember;
tableProperties.TryGetValue(columnName, false, out columnMember);
if (columnMember == null)
{
AddToSchemaErrorsWithMemberInfo(Strings.Mapping_InvalidContent_Column, columnName,
StorageMappingErrorCode.InvalidStorageMember, m_sourceLocation, xmlLineInfoNav, m_parsingErrors);
}
//Don't create scalar property map if the property or column metadata is null
if ((member == null) || (columnMember == null))
{
return null;
}
if (!Helper.IsScalarType(member.TypeUsage.EdmType))
{
EdmSchemaError error = new EdmSchemaError(
Strings.Mapping_Invalid_CSide_ScalarProperty(
member.Name),
(int)StorageMappingErrorCode.InvalidTypeInScalarProperty,
EdmSchemaErrorSeverity.Error,
m_sourceLocation,
xmlLineInfoNav.LineNumber,
xmlLineInfoNav.LinePosition);
m_parsingErrors.Add(error);
return null;
}
ValidateAndUpdateScalarMemberMapping(member, columnMember, xmlLineInfoNav);
StorageScalarPropertyMapping scalarPropertyMapping = new StorageScalarPropertyMapping(member, columnMember);
return scalarPropertyMapping;
}
/// <summary>
/// The method loads the ComplexProperty mapping into the internal datastructures.
/// </summary>
private StorageComplexPropertyMapping LoadComplexPropertyMapping(XPathNavigator nav, EdmType containerType, ReadOnlyMetadataCollection<EdmProperty> tableProperties)
{
IXmlLineInfo navLineInfo = (IXmlLineInfo)nav;
CollectionType collectionType = containerType as CollectionType;
//Get the property name from MSL
string propertyName = GetAliasResolvedAttributeValue(nav.Clone(), StorageMslConstructs.ComplexPropertyNameAttribute);
//Get the member metadata from the contianer type passed in.
//But if the continer type is collection type, there would n't be any member to represent the member.
EdmProperty member = null;
EdmType memberType = null;
//If member specified the type name, it takes precedence
string memberTypeName = GetAliasResolvedAttributeValue(nav.Clone(), StorageMslConstructs.ComplexTypeMappingTypeNameAttribute);
StructuralType containerStructuralType = containerType as StructuralType;
if (String.IsNullOrEmpty(memberTypeName))
{
if (collectionType == null)
{
if (containerStructuralType != null)
{
EdmMember tempMember;
containerStructuralType.Members.TryGetValue(propertyName, false /*ignoreCase*/, out tempMember);
member = tempMember as EdmProperty;
if (member == null)
{
AddToSchemaErrorsWithMemberInfo(Strings.Mapping_InvalidContent_Cdm_Member, propertyName,
StorageMappingErrorCode.InvalidEdmMember, m_sourceLocation, navLineInfo, m_parsingErrors);
}
memberType = member.TypeUsage.EdmType;
}
else
{
AddToSchemaErrorsWithMemberInfo(Strings.Mapping_InvalidContent_Cdm_Member, propertyName,
StorageMappingErrorCode.InvalidEdmMember, m_sourceLocation, navLineInfo, m_parsingErrors);
}
}
else
{
memberType = collectionType.TypeUsage.EdmType;
}
}
else
{
//If container type is null that means we have not found the member in any of the IsOfTypes.
if (containerType != null)
{
EdmMember tempMember;
containerStructuralType.Members.TryGetValue(propertyName, false /*ignoreCase*/, out tempMember);
member = tempMember as EdmProperty;
}
if (member == null)
{
AddToSchemaErrorsWithMemberInfo(Strings.Mapping_InvalidContent_Cdm_Member, propertyName,
StorageMappingErrorCode.InvalidEdmMember, m_sourceLocation, navLineInfo, m_parsingErrors);
}
this.EdmItemCollection.TryGetItem<EdmType>(memberTypeName, out memberType);
memberType = memberType as ComplexType;
// If member type is null, that means the type wasn't found in the workspace
if (memberType == null)
{
AddToSchemaErrorsWithMemberInfo(Strings.Mapping_InvalidContent_Complex_Type, memberTypeName,
StorageMappingErrorCode.InvalidComplexType, m_sourceLocation, navLineInfo, m_parsingErrors);
}
}
StorageComplexPropertyMapping complexPropertyMapping = new StorageComplexPropertyMapping(member);
XPathNavigator cloneNav = nav.Clone();
bool hasComplexTypeMappingElements = false;
if (cloneNav.MoveToChild(XPathNodeType.Element))
{
if (cloneNav.LocalName == StorageMslConstructs.ComplexTypeMappingElement)
{
hasComplexTypeMappingElements = true;
}
}
//There is no point in continuing if the complex member or complex member type is null
if ((member == null) || (memberType == null))
{
return null;
}
if (hasComplexTypeMappingElements)
{
nav.MoveToChild(XPathNodeType.Element);
do
{
complexPropertyMapping.AddTypeMapping(LoadComplexTypeMapping(nav.Clone(), null, tableProperties));
}
while (nav.MoveToNext(XPathNodeType.Element));
}
else
{
complexPropertyMapping.AddTypeMapping(LoadComplexTypeMapping(nav.Clone(), memberType, tableProperties));
}
return complexPropertyMapping;
}
private StorageComplexTypeMapping LoadComplexTypeMapping(XPathNavigator nav, EdmType type, ReadOnlyMetadataCollection<EdmProperty> tableType)
{
//Get the IsPartial attribute from MSL
bool isPartial = false;
string partialAttribute = StorageMappingItemLoader.GetAttributeValue(nav.Clone(), StorageMslConstructs.ComplexPropertyIsPartialAttribute);
if (!String.IsNullOrEmpty(partialAttribute))
{
//XSD validation should have guarenteed that the attribute value can only be true or false
Debug.Assert(partialAttribute == "true" || partialAttribute == "false");
isPartial = Convert.ToBoolean(partialAttribute, System.Globalization.CultureInfo.InvariantCulture);
}
//Create an ComplexTypeMapping to hold the information for Type mapping.
StorageComplexTypeMapping typeMapping = new StorageComplexTypeMapping(isPartial);
if (type != null)
{
typeMapping.AddType(type as ComplexType);
}
else
{
Debug.Assert(nav.LocalName == StorageMslConstructs.ComplexTypeMappingElement);
string typeName = GetAliasResolvedAttributeValue(nav.Clone(), StorageMslConstructs.ComplexTypeMappingTypeNameAttribute);
int index = typeName.IndexOf(StorageMslConstructs.TypeNameSperator);
string currentTypeName = null;
do
{
if (index != -1)
{
currentTypeName = typeName.Substring(0, index);
typeName = typeName.Substring(index + 1, (typeName.Length - (index + 1)));
}
else
{
currentTypeName = typeName;
typeName = string.Empty;
}
int isTypeOfIndex = currentTypeName.IndexOf(StorageMslConstructs.IsTypeOf, StringComparison.Ordinal);
if (isTypeOfIndex == 0)
{
currentTypeName = currentTypeName.Substring(StorageMslConstructs.IsTypeOf.Length, (currentTypeName.Length - (StorageMslConstructs.IsTypeOf.Length + 1)));
currentTypeName = GetAliasResolvedValue(currentTypeName);
}
else
{
currentTypeName = GetAliasResolvedValue(currentTypeName);
}
ComplexType complexType;
this.EdmItemCollection.TryGetItem<ComplexType>(currentTypeName, out complexType);
if (complexType == null)
{
AddToSchemaErrorsWithMemberInfo(Strings.Mapping_InvalidContent_Complex_Type, currentTypeName,
StorageMappingErrorCode.InvalidComplexType, m_sourceLocation, (IXmlLineInfo)nav, m_parsingErrors);
index = typeName.IndexOf(StorageMslConstructs.TypeNameSperator);
continue;
}
if (isTypeOfIndex == 0)
{
typeMapping.AddIsOfType(complexType);
}
else
{
typeMapping.AddType(complexType);
}
index = typeName.IndexOf(StorageMslConstructs.TypeNameSperator);
} while (typeName.Length != 0);
}
//Now load the children of ComplexTypeMapping
if (nav.MoveToChild(XPathNodeType.Element))
{
do
{
EdmType containerType = typeMapping.GetOwnerType(StorageMappingItemLoader.GetAttributeValue(nav.Clone(), StorageMslConstructs.ComplexPropertyNameAttribute));
switch (nav.LocalName)
{
case StorageMslConstructs.ScalarPropertyElement:
StorageScalarPropertyMapping scalarMap =
LoadScalarPropertyMapping(nav.Clone(), containerType, tableType);
//ScalarMap can be null in case of invalid MSL files
if (scalarMap != null)
{
typeMapping.AddProperty(scalarMap);
}
break;
case StorageMslConstructs.ComplexPropertyElement:
StorageComplexPropertyMapping complexMap =
LoadComplexPropertyMapping(nav.Clone(), containerType, tableType);
//complexMap can be null in case of invalid maps
if (complexMap != null)
{
typeMapping.AddProperty(complexMap);
}
break;
case StorageMslConstructs.ConditionElement:
StorageConditionPropertyMapping conditionMap =
LoadConditionPropertyMapping(nav.Clone(), containerType, tableType);
if (conditionMap != null)
{
typeMapping.AddConditionProperty(conditionMap, duplicateMemberConditionError: (member) =>
{
AddToSchemaErrorsWithMemberInfo(
Strings.Mapping_InvalidContent_Duplicate_Condition_Member, member.Name,
StorageMappingErrorCode.ConditionError,
m_sourceLocation, (IXmlLineInfo)nav, m_parsingErrors);
});
}
break;
default:
throw System.Data.Entity.Error.NotSupported();
}
} while (nav.MoveToNext(XPathNodeType.Element));
}
return typeMapping;
}
/// <summary>
/// The method loads the EndProperty mapping
/// into the internal datastructures.
/// </summary>
/// <param name="nav"></param>
/// <param name="end"></param>
/// <param name="tableType"></param>
/// <returns></returns>
private StorageEndPropertyMapping LoadEndPropertyMapping(XPathNavigator nav, AssociationEndMember end, EntityType tableType)
{
//FutureEnhancement : Change End Property Mapping to not derive from
// StoragePropertyMapping
StorageEndPropertyMapping endMapping = new StorageEndPropertyMapping(null);
endMapping.EndMember = end;
nav.MoveToChild(XPathNodeType.Element);
do
{
switch (nav.LocalName)
{
case StorageMslConstructs.ScalarPropertyElement:
RefType endRef = end.TypeUsage.EdmType as RefType;
Debug.Assert(endRef != null);
EntityTypeBase containerType = endRef.ElementType;
StorageScalarPropertyMapping scalarMap = LoadScalarPropertyMapping(nav.Clone(), containerType, tableType.Properties);
//Scalar Property Mapping can be null
//in case of invalid MSL files.
if (scalarMap != null)
{
//Make sure that the properties mapped as part of EndProperty maps are the key properties.
//If any other property is mapped, we should raise an error.
if (!containerType.KeyMembers.Contains(scalarMap.EdmProperty))
{
IXmlLineInfo navLineInfo = (IXmlLineInfo)nav;
AddToSchemaErrorsWithMemberInfo(Strings.Mapping_InvalidContent_EndProperty, scalarMap.EdmProperty.Name,
StorageMappingErrorCode.InvalidEdmMember, m_sourceLocation, navLineInfo, m_parsingErrors);
return null;
}
endMapping.AddProperty(scalarMap);
}
break;
default:
Debug.Fail("XSD validation should have ensured that End EdmProperty Maps only have Schalar properties");
break;
}
} while (nav.MoveToNext(XPathNodeType.Element));
return endMapping;
}
/// <summary>
/// The method loads the ConditionProperty mapping
/// into the internal datastructures.
/// </summary>
/// <param name="nav"></param>
/// <param name="containerType"></param>
/// <param name="tableType"></param>
/// <returns></returns>
private StorageConditionPropertyMapping LoadConditionPropertyMapping(XPathNavigator nav, EdmType containerType, ReadOnlyMetadataCollection<EdmProperty> tableProperties)
{
//Get the CDM side property name.
string propertyName = GetAliasResolvedAttributeValue(nav.Clone(), StorageMslConstructs.ConditionNameAttribute);
//Get the Store side property name from Storeside
string columnName = GetAliasResolvedAttributeValue(nav.Clone(), StorageMslConstructs.ConditionColumnNameAttribute);
IXmlLineInfo navLineInfo = (IXmlLineInfo)nav;
//Either the property name or column name can be specified but both can not be.
if ((propertyName != null) && (columnName != null))
{
AddToSchemaErrors(Strings.Mapping_InvalidContent_ConditionMapping_Both_Members,
StorageMappingErrorCode.ConditionError, m_sourceLocation, navLineInfo, m_parsingErrors);
return null;
}
if ((propertyName == null) && (columnName == null))
{
AddToSchemaErrors(Strings.Mapping_InvalidContent_ConditionMapping_Either_Members,
StorageMappingErrorCode.ConditionError, m_sourceLocation, navLineInfo, m_parsingErrors);
return null;
}
EdmProperty member = null;
//Get the CDM EdmMember reprsented by the name specified.
if (propertyName != null)
{
EdmMember tempMember;
//If container type is null that means we have not found the member in any of the IsOfTypes.
if (containerType != null)
{
((StructuralType)containerType).Members.TryGetValue(propertyName, false /*ignoreCase*/, out tempMember);
member = tempMember as EdmProperty;
}
}
//Get the column EdmMember represented by the column name specified
EdmProperty columnMember = null;
if (columnName != null)
{
tableProperties.TryGetValue(columnName, false, out columnMember);
}
//Get the member for which the condition is being specified
EdmProperty conditionMember = (columnMember != null) ? columnMember : member;
if (conditionMember == null)
{
AddToSchemaErrorsWithMemberInfo(Strings.Mapping_InvalidContent_ConditionMapping_InvalidMember, ((columnName != null) ? columnName : propertyName),
StorageMappingErrorCode.ConditionError, m_sourceLocation, navLineInfo, m_parsingErrors);
return null;
}
Nullable<bool> isNullValue = null;
object value = null;
//Get the attribute value for IsNull attribute
string isNullAttribute = StorageMappingItemLoader.GetAttributeValue(nav.Clone(), StorageMslConstructs.ConditionIsNullAttribute);
//Get strongly Typed value if the condition was specified for a specific condition
EdmType edmType = conditionMember.TypeUsage.EdmType;
if (Helper.IsPrimitiveType(edmType))
{
//Decide if the member is of a type that we would allow a condition on.
//First convert the type to C space, if this is a condition in s space( before checking this).
TypeUsage cspaceTypeUsage;
if (conditionMember.DeclaringType.DataSpace == DataSpace.SSpace)
{
cspaceTypeUsage = StoreItemCollection.StoreProviderManifest.GetEdmType(conditionMember.TypeUsage);
if (cspaceTypeUsage == null)
{
AddToSchemaErrorWithMessage(Strings.Mapping_ProviderReturnsNullType(conditionMember.Name),
StorageMappingErrorCode.MappingStoreProviderReturnsNullEdmType,
m_sourceLocation, navLineInfo, m_parsingErrors);
return null;
}
}
else
{
cspaceTypeUsage = conditionMember.TypeUsage;
}
PrimitiveType memberType = ((PrimitiveType)cspaceTypeUsage.EdmType);
Type clrMemberType = memberType.ClrEquivalentType;
PrimitiveTypeKind primitiveTypeKind = memberType.PrimitiveTypeKind;
//Only a subset of primitive types can be used in Conditions that are specified over values.
//IsNull conditions can be specified on any primitive types
if ((isNullAttribute == null) && !IsTypeSupportedForCondition(primitiveTypeKind))
{
AddToSchemaErrorWithMemberAndStructure(Strings.Mapping_InvalidContent_ConditionMapping_InvalidPrimitiveTypeKind,
conditionMember.Name, edmType.FullName, StorageMappingErrorCode.ConditionError,
m_sourceLocation, navLineInfo, m_parsingErrors);
return null;
}
Debug.Assert(clrMemberType != null, "Scalar Types should have associated clr type");
//If the value is not compatible with the type, just add an error and return
if(!StorageMappingItemLoader.TryGetTypedAttributeValue(nav.Clone(), StorageMslConstructs.ConditionValueAttribute, clrMemberType, m_sourceLocation, m_parsingErrors, out value))
{
return null;
}
}
else if (Helper.IsEnumType(edmType))
{
// Enumeration type - get the actual value
value = StorageMappingItemLoader.GetEnumAttributeValue(nav.Clone(), StorageMslConstructs.ConditionValueAttribute, (EnumType)edmType, m_sourceLocation, m_parsingErrors);
}
else
{
// Since NullableComplexTypes are not being supported,
// we don't allow conditions on complex types
AddToSchemaErrors(Strings.Mapping_InvalidContent_ConditionMapping_NonScalar,
StorageMappingErrorCode.ConditionError, m_sourceLocation, navLineInfo, m_parsingErrors);
return null;
}
//Either Value or NotNull need to be specifid on the condition mapping but not both
if ((isNullAttribute != null) && (value != null))
{
AddToSchemaErrors(Strings.Mapping_InvalidContent_ConditionMapping_Both_Values,
StorageMappingErrorCode.ConditionError, m_sourceLocation, navLineInfo, m_parsingErrors);
return null;
}
if ((isNullAttribute == null) && (value == null))
{
AddToSchemaErrors(Strings.Mapping_InvalidContent_ConditionMapping_Either_Values,
StorageMappingErrorCode.ConditionError, m_sourceLocation, navLineInfo, m_parsingErrors);
return null;
}
if (isNullAttribute != null)
{
//XSD validation should have guarenteed that the attribute value can only be true or false
Debug.Assert(isNullAttribute == "true" || isNullAttribute == "false");
isNullValue = Convert.ToBoolean(isNullAttribute, System.Globalization.CultureInfo.InvariantCulture);
}
if (columnMember != null && (columnMember.IsStoreGeneratedComputed || columnMember.IsStoreGeneratedIdentity))
{
AddToSchemaErrorsWithMemberInfo(Strings.Mapping_InvalidContent_ConditionMapping_Computed, columnMember.Name,
StorageMappingErrorCode.ConditionError, m_sourceLocation, navLineInfo, m_parsingErrors);
return null;
}
StorageConditionPropertyMapping conditionPropertyMapping = new StorageConditionPropertyMapping(member, columnMember, value, isNullValue);
return conditionPropertyMapping;
}
internal static bool IsTypeSupportedForCondition(PrimitiveTypeKind primitiveTypeKind)
{
switch (primitiveTypeKind)
{
case PrimitiveTypeKind.Boolean:
case PrimitiveTypeKind.Byte:
case PrimitiveTypeKind.Int16:
case PrimitiveTypeKind.Int32:
case PrimitiveTypeKind.Int64:
case PrimitiveTypeKind.String:
case PrimitiveTypeKind.SByte:
return true;
case PrimitiveTypeKind.Binary:
case PrimitiveTypeKind.DateTime:
case PrimitiveTypeKind.Time:
case PrimitiveTypeKind.DateTimeOffset:
case PrimitiveTypeKind.Double:
case PrimitiveTypeKind.Guid:
case PrimitiveTypeKind.Single:
case PrimitiveTypeKind.Decimal:
return false;
default:
Debug.Fail("New primitive type kind added?");
return false;
}
}
private static XmlSchemaSet GetOrCreateSchemaSet()
{
if (s_mappingXmlSchema == null)
{
//Get the xsd stream for CS MSL Xsd.
XmlSchemaSet set = new XmlSchemaSet();
AddResourceXsdToSchemaSet(set, StorageMslConstructs.ResourceXsdNameV1);
AddResourceXsdToSchemaSet(set, StorageMslConstructs.ResourceXsdNameV2);
AddResourceXsdToSchemaSet(set, StorageMslConstructs.ResourceXsdNameV3);
System.Threading.Interlocked.CompareExchange(ref s_mappingXmlSchema, set, null);
}
return s_mappingXmlSchema;
}
private static void AddResourceXsdToSchemaSet(XmlSchemaSet set, string resourceName)
{
using (XmlReader xsdReader = System.Data.Common.DbProviderServices.GetXmlResource(resourceName))
{
XmlSchema xmlSchema = XmlSchema.Read(xsdReader, null);
set.Add(xmlSchema);
}
}
/// <summary>
/// Throws a new MappingException giving out the line number and
/// File Name where the error in Mapping specification is present.
/// </summary>
/// <param name="message"></param>
/// <param name="errorCode"></param>
/// <param name="uri"></param>
/// <param name="lineInfo"></param>
/// <param name="parsingErrors">Error Collection where the parsing errors are collected</param>
private static void AddToSchemaErrors(string message, StorageMappingErrorCode errorCode, string location, IXmlLineInfo lineInfo, IList<EdmSchemaError> parsingErrors)
{
EdmSchemaError error = new EdmSchemaError(message, (int)errorCode, EdmSchemaErrorSeverity.Error, location, lineInfo.LineNumber, lineInfo.LinePosition);
parsingErrors.Add(error);
}
private static EdmSchemaError AddToSchemaErrorsWithMemberInfo(Func<object, string> messageFormat, string errorMember, StorageMappingErrorCode errorCode, string location, IXmlLineInfo lineInfo, IList<EdmSchemaError> parsingErrors)
{
EdmSchemaError error = new EdmSchemaError(messageFormat(errorMember), (int)errorCode, EdmSchemaErrorSeverity.Error, location, lineInfo.LineNumber, lineInfo.LinePosition);
parsingErrors.Add(error);
return error;
}
private static void AddToSchemaErrorWithMemberAndStructure(Func<object, object, string> messageFormat, string errorMember,
string errorStructure, StorageMappingErrorCode errorCode, string location, IXmlLineInfo lineInfo, IList<EdmSchemaError> parsingErrors)
{
EdmSchemaError error = new EdmSchemaError(
messageFormat(errorMember, errorStructure)
, (int)errorCode, EdmSchemaErrorSeverity.Error, location, lineInfo.LineNumber, lineInfo.LinePosition);
parsingErrors.Add(error);
}
private static void AddToSchemaErrorWithMessage(string errorMessage, StorageMappingErrorCode errorCode, string location, IXmlLineInfo lineInfo, IList<EdmSchemaError> parsingErrors)
{
EdmSchemaError error = new EdmSchemaError(errorMessage, (int)errorCode, EdmSchemaErrorSeverity.Error, location, lineInfo.LineNumber, lineInfo.LinePosition);
parsingErrors.Add(error);
}
/// <summary>
/// Resolve the attribute value based on the aliases provided as part of MSL file.
/// </summary>
/// <param name="nav"></param>
/// <param name="attributeName"></param>
/// <returns></returns>
private string GetAliasResolvedAttributeValue(XPathNavigator nav, string attributeName)
{
return GetAliasResolvedValue(StorageMappingItemLoader.GetAttributeValue(nav, attributeName));
}
/// <summary>
///
/// </summary>
/// <param name="nav"></param>
/// <param name="attributeName"></param>
/// <returns></returns>
private bool GetBoolAttributeValue(XPathNavigator nav, string attributeName, bool defaultValue)
{
bool boolValue = defaultValue;
object boolObj = Helper.GetTypedAttributeValue(nav, attributeName, typeof(bool));
if (boolObj != null)
{
boolValue = (bool)boolObj;
}
return boolValue;
}
/// <summary>
/// The method simply calls the helper method on Helper class with the
/// namespaceURI that is default for CSMapping.
/// </summary>
/// <param name="nav"></param>
/// <param name="attributeName"></param>
/// <returns></returns>
private static string GetAttributeValue(XPathNavigator nav, string attributeName)
{
return Helper.GetAttributeValue(nav, attributeName);
}
/// <summary>
/// The method simply calls the helper method on Helper class with the
/// namespaceURI that is default for CSMapping.
/// </summary>
/// <param name="nav"></param>
/// <param name="attributeName"></param>
/// <param name="clrType"></param>
/// <param name="uri"></param>
/// <param name="parsingErrors">Error Collection where the parsing errors are collected</param>
/// <returns></returns>
private static bool TryGetTypedAttributeValue(XPathNavigator nav, string attributeName, Type clrType, string sourceLocation, IList<EdmSchemaError> parsingErrors, out object value)
{
value = null;
try
{
value = Helper.GetTypedAttributeValue(nav, attributeName, clrType);
}
catch (FormatException)
{
StorageMappingItemLoader.AddToSchemaErrors(Strings.Mapping_ConditionValueTypeMismatch,
StorageMappingErrorCode.ConditionError, sourceLocation, (IXmlLineInfo)nav, parsingErrors);
return false;
}
return true;
}
/// <summary>
/// Returns the enum EdmMember corresponding to attribute name in enumType.
/// </summary>
/// <param name="nav"></param>
/// <param name="attributeName"></param>
/// <param name="enumType"></param>
/// <param name="uri"></param>
/// <param name="parsingErrors">Error Collection where the parsing errors are collected</param>
/// <returns></returns>
private static EnumMember GetEnumAttributeValue(XPathNavigator nav, string attributeName, EnumType enumType, string sourceLocation, IList<EdmSchemaError> parsingErrors)
{
IXmlLineInfo xmlLineInfoNav = (IXmlLineInfo)nav;
string value = GetAttributeValue(nav, attributeName);
if (String.IsNullOrEmpty(value))
{
StorageMappingItemLoader.AddToSchemaErrorsWithMemberInfo(Strings.Mapping_Enum_EmptyValue, enumType.FullName,
StorageMappingErrorCode.InvalidEnumValue, sourceLocation, xmlLineInfoNav, parsingErrors);
}
EnumMember result;
bool found = enumType.Members.TryGetValue(value, false, out result);
if (!found)
{
StorageMappingItemLoader.AddToSchemaErrorsWithMemberInfo(Strings.Mapping_Enum_InvalidValue, value,
StorageMappingErrorCode.InvalidEnumValue, sourceLocation, xmlLineInfoNav, parsingErrors);
}
return result;
}
/// <summary>
/// Resolve the string value based on the aliases provided as part of MSL file.
/// </summary>
/// <param name="aliasedString"></param>
/// <returns></returns>
private string GetAliasResolvedValue(string aliasedString)
{
if ((aliasedString == null) || (aliasedString.Length == 0))
return aliasedString;
//For now all attributes have no namespace
int aliasIndex = aliasedString.LastIndexOf('.');
//If no '.' in the string, than obviously the string is not aliased
if (aliasIndex == -1)
return aliasedString;
string aliasKey = aliasedString.Substring(0, aliasIndex);
string aliasValue;
m_alias.TryGetValue(aliasKey, out aliasValue);
if (aliasValue != null)
{
aliasedString = aliasValue + aliasedString.Substring(aliasIndex);
}
return aliasedString;
}
/// <summary>
/// Creates Xml Reader with settings required for
/// XSD validation.
/// </summary>
/// <param name="innerReader"></param>
private XmlReader GetSchemaValidatingReader(XmlReader innerReader)
{
//Create the reader setting that will be used while
//loading the MSL.
XmlReaderSettings readerSettings = GetXmlReaderSettings();
XmlReader reader = XmlReader.Create(innerReader, readerSettings);
return reader;
}
private XmlReaderSettings GetXmlReaderSettings()
{
XmlReaderSettings readerSettings = System.Data.EntityModel.SchemaObjectModel.Schema.CreateEdmStandardXmlReaderSettings();
readerSettings.ValidationFlags |= System.Xml.Schema.XmlSchemaValidationFlags.ReportValidationWarnings;
readerSettings.ValidationEventHandler += this.XsdValidationCallBack;
readerSettings.ValidationType = ValidationType.Schema;
readerSettings.Schemas = GetOrCreateSchemaSet();
return readerSettings;
}
/// <summary>
/// The method is called by the XSD validation event handler when
/// ever there are warnings or errors.
/// We ignore the warnings but the errors will result in exception.
/// </summary>
/// <param name="sender"></param>
/// <param name="args"></param>
private void XsdValidationCallBack(object sender, ValidationEventArgs args)
{
if (args.Severity != XmlSeverityType.Warning)
{
string sourceLocation = null;
if (!string.IsNullOrEmpty(args.Exception.SourceUri))
{
sourceLocation = Helper.GetFileNameFromUri(new Uri(args.Exception.SourceUri));
}
EdmSchemaErrorSeverity severity = EdmSchemaErrorSeverity.Error;
if (args.Severity == XmlSeverityType.Warning)
severity = EdmSchemaErrorSeverity.Warning;
EdmSchemaError error = new EdmSchemaError(Strings.Mapping_InvalidMappingSchema_validation(args.Exception.Message)
, (int)StorageMappingErrorCode.XmlSchemaValidationError, severity, sourceLocation, args.Exception.LineNumber, args.Exception.LinePosition);
m_parsingErrors.Add(error);
}
}
/// <summary>
/// Validate the scalar property mapping - makes sure that the cspace type is promotable to the store side and updates
/// the store type usage
/// </summary>
/// <param name="member"></param>
/// <param name="columnMember"></param>
/// <param name="lineInfo"></param>
private void ValidateAndUpdateScalarMemberMapping(EdmProperty member, EdmProperty columnMember, IXmlLineInfo lineInfo)
{
Debug.Assert(
Helper.IsScalarType(member.TypeUsage.EdmType),
"c-space member type must be of primitive or enumeration type");
Debug.Assert(Helper.IsPrimitiveType(columnMember.TypeUsage.EdmType), "s-space column type must be primitive");
KeyValuePair<TypeUsage, TypeUsage> memberMappingInfo;
if (!m_scalarMemberMappings.TryGetValue(member, out memberMappingInfo))
{
int errorCount = m_parsingErrors.Count;
// Validates that the CSpace member type is promotable to the SSpace member types and returns a typeUsage which contains
// the store equivalent type for the CSpace member type.
// For e.g. If a CSpace member of type Edm.Int32 maps to SqlServer.Int64, the return type usage will contain SqlServer.int
// which is store equivalent type for Edm.Int32
TypeUsage storeEquivalentTypeUsage = Helper.ValidateAndConvertTypeUsage(member,
columnMember, lineInfo, m_sourceLocation, m_parsingErrors, StoreItemCollection);
// If the cspace type is not compatible with the store type, add a schema error and return
if (storeEquivalentTypeUsage == null)
{
if (errorCount == m_parsingErrors.Count)
{
EdmSchemaError error = new EdmSchemaError(
GetInvalidMemberMappingErrorMessage(member, columnMember),
(int)StorageMappingErrorCode.IncompatibleMemberMapping, EdmSchemaErrorSeverity.Error,
m_sourceLocation, lineInfo.LineNumber,
lineInfo.LinePosition);
m_parsingErrors.Add(error);
}
}
else
{
m_scalarMemberMappings.Add(member, new KeyValuePair<TypeUsage, TypeUsage>(storeEquivalentTypeUsage, columnMember.TypeUsage));
}
}
else
{
// Get the store member type to which the cspace member was mapped to previously
TypeUsage storeMappedTypeUsage = memberMappingInfo.Value;
TypeUsage modelColumnMember = columnMember.TypeUsage.GetModelTypeUsage();
if (!Object.ReferenceEquals(columnMember.TypeUsage.EdmType, storeMappedTypeUsage.EdmType))
{
EdmSchemaError error = new EdmSchemaError(
Strings.Mapping_StoreTypeMismatch_ScalarPropertyMapping(
member.Name,
storeMappedTypeUsage.EdmType.Name),
(int)StorageMappingErrorCode.CSpaceMemberMappedToMultipleSSpaceMemberWithDifferentTypes,
EdmSchemaErrorSeverity.Error,
m_sourceLocation,
lineInfo.LineNumber,
lineInfo.LinePosition);
m_parsingErrors.Add(error);
}
// Check if the cspace facets are promotable to the new store type facets
else if (!TypeSemantics.IsSubTypeOf(ResolveTypeUsageForEnums(member.TypeUsage), modelColumnMember))
{
EdmSchemaError error = new EdmSchemaError(
GetInvalidMemberMappingErrorMessage(member, columnMember),
(int)StorageMappingErrorCode.IncompatibleMemberMapping, EdmSchemaErrorSeverity.Error,
m_sourceLocation, lineInfo.LineNumber,
lineInfo.LinePosition);
m_parsingErrors.Add(error);
}
}
}
private string GetInvalidMemberMappingErrorMessage(EdmMember cSpaceMember, EdmMember sSpaceMember)
{
return Strings.Mapping_Invalid_Member_Mapping(
cSpaceMember.TypeUsage.EdmType + GetFacetsForDisplay(cSpaceMember.TypeUsage),
cSpaceMember.Name,
cSpaceMember.DeclaringType.FullName,
sSpaceMember.TypeUsage.EdmType + GetFacetsForDisplay(sSpaceMember.TypeUsage),
sSpaceMember.Name,
sSpaceMember.DeclaringType.FullName);
}
private string GetFacetsForDisplay(TypeUsage typeUsage)
{
Debug.Assert(typeUsage != null);
ReadOnlyMetadataCollection<Facet> facets = typeUsage.Facets;
if (facets == null || facets.Count == 0)
{
return string.Empty;
}
int numFacets = facets.Count;
StringBuilder facetDisplay = new StringBuilder("[");
for (int i = 0; i < numFacets-1; ++i)
{
facetDisplay.AppendFormat("{0}={1},", facets[i].Name, facets[i].Value ?? string.Empty);
}
facetDisplay.AppendFormat("{0}={1}]", facets[numFacets - 1].Name, facets[numFacets-1].Value ?? string.Empty);
return facetDisplay.ToString();
}
#endregion
#region Nested types
/// <summary>
/// Encapsulates state and functionality for loading a modification function mapping.
/// </summary>
private class ModificationFunctionMappingLoader
{
// Storage mapping loader
private readonly StorageMappingItemLoader m_parentLoader;
// Mapped function
private EdmFunction m_function;
// Entity set mapped by this function (may be null)
private readonly EntitySet m_entitySet;
// Association set mapped by this function (may be null)
private readonly AssociationSet m_associationSet;
// Model entity container (used to resolve set names)
private readonly EntityContainer m_modelContainer;
// Item collection (used to resolve function and type names)
private readonly EdmItemCollection m_edmItemCollection;
// Item collection (used to resolve function and type names)
private readonly StoreItemCollection m_storeItemCollection;
// Indicates whether the function can be bound to "current"
// versions of properties (i.e., inserts and updates)
private bool m_allowCurrentVersion;
// Indicates whether the function can be bound to "original"
// versions of properties (i.e., deletes and updates)
private bool m_allowOriginalVersion;
// Tracks which function parameters have been seen so far.
private readonly Set<FunctionParameter> m_seenParameters;
// Tracks members navigated to arrive at the current element
private readonly Stack<EdmMember> m_members;
// When set, indicates we are interpreting a navigation property on the given set.
private AssociationSet m_associationSetNavigation;
// Initialize loader
internal ModificationFunctionMappingLoader(
StorageMappingItemLoader parentLoader,
EntitySetBase extent)
{
m_parentLoader = EntityUtil.CheckArgumentNull(parentLoader, "parentLoader");
// initialize member fields
m_modelContainer = EntityUtil.CheckArgumentNull<EntitySetBase>(extent, "extent").EntityContainer;
m_edmItemCollection = parentLoader.EdmItemCollection;
m_storeItemCollection = parentLoader.StoreItemCollection;
m_entitySet = extent as EntitySet;
if (null == m_entitySet)
{
// do a cast here since the extent must either be an entity set
// or an association set
m_associationSet = (AssociationSet)extent;
}
m_seenParameters = new Set<FunctionParameter>();
m_members = new Stack<EdmMember>();
}
internal StorageModificationFunctionMapping LoadEntityTypeModificationFunctionMapping(XPathNavigator nav, EntitySetBase entitySet, bool allowCurrentVersion, bool allowOriginalVersion, EntityType entityType)
{
FunctionParameter rowsAffectedParameter;
m_function = LoadAndValidateFunctionMetadata(nav.Clone(), out rowsAffectedParameter);
if (m_function == null)
{
return null;
}
m_allowCurrentVersion = allowCurrentVersion;
m_allowOriginalVersion = allowOriginalVersion;
// Load all parameter bindings and result bindings
IEnumerable<StorageModificationFunctionParameterBinding> parameters = LoadParameterBindings(nav.Clone(), entityType);
IEnumerable<StorageModificationFunctionResultBinding> resultBindings = LoadResultBindings(nav.Clone(), entityType);
StorageModificationFunctionMapping functionMapping = new StorageModificationFunctionMapping(entitySet, entityType, m_function, parameters, rowsAffectedParameter, resultBindings);
return functionMapping;
}
// Loads a function mapping for an association set
internal StorageModificationFunctionMapping LoadAssociationSetModificationFunctionMapping(XPathNavigator nav, EntitySetBase entitySet, bool isInsert)
{
FunctionParameter rowsAffectedParameter;
m_function = LoadAndValidateFunctionMetadata(nav.Clone(), out rowsAffectedParameter);
if (m_function == null)
{
return null;
}
if (isInsert)
{
m_allowCurrentVersion = true;
m_allowOriginalVersion = false;
}
else
{
m_allowCurrentVersion = false;
m_allowOriginalVersion = true;
}
// Load all parameter bindings
IEnumerable<StorageModificationFunctionParameterBinding> parameters = LoadParameterBindings(nav.Clone(), m_associationSet.ElementType);
StorageModificationFunctionMapping mapping = new StorageModificationFunctionMapping(entitySet, entitySet.ElementType, m_function, parameters, rowsAffectedParameter, null);
return mapping;
}
// Loads all result bindings.
private IEnumerable<StorageModificationFunctionResultBinding> LoadResultBindings(XPathNavigator nav, EntityType entityType)
{
List<StorageModificationFunctionResultBinding> resultBindings = new List<StorageModificationFunctionResultBinding>();
IXmlLineInfo xmlLineInfoNav = (IXmlLineInfo)nav;
// walk through all children, filtering on result bindings
if (nav.MoveToChild(XPathNodeType.Element))
{
do
{
if (nav.LocalName == StorageMslConstructs.ResultBindingElement)
{
// retrieve attributes
string propertyName = m_parentLoader.GetAliasResolvedAttributeValue(nav.Clone(),
StorageMslConstructs.ResultBindingPropertyNameAttribute);
string columnName = m_parentLoader.GetAliasResolvedAttributeValue(nav.Clone(),
StorageMslConstructs.ScalarPropertyColumnNameAttribute);
// resolve metadata
EdmProperty property = null;
if (null == propertyName ||
!entityType.Properties.TryGetValue(propertyName, false, out property))
{
// add a schema error and return if the property does not exist
StorageMappingItemLoader.AddToSchemaErrorWithMemberAndStructure(
Strings.Mapping_ModificationFunction_PropertyNotFound,
propertyName, entityType.Name,
StorageMappingErrorCode.InvalidEdmMember, m_parentLoader.m_sourceLocation,
xmlLineInfoNav, m_parentLoader.m_parsingErrors);
return new List<StorageModificationFunctionResultBinding>();
}
// construct element binding (no type checking is required at mapping load time)
StorageModificationFunctionResultBinding resultBinding = new StorageModificationFunctionResultBinding(columnName, property);
resultBindings.Add(resultBinding);
}
} while (nav.MoveToNext(XPathNodeType.Element));
}
// check for duplicate mappings of single properties
KeyToListMap<EdmProperty, string> propertyToColumnNamesMap = new KeyToListMap<EdmProperty, string>(EqualityComparer<EdmProperty>.Default);
foreach (StorageModificationFunctionResultBinding resultBinding in resultBindings)
{
propertyToColumnNamesMap.Add(resultBinding.Property, resultBinding.ColumnName);
}
foreach (EdmProperty property in propertyToColumnNamesMap.Keys)
{
ReadOnlyCollection<string> columnNames = propertyToColumnNamesMap.ListForKey(property);
if (1 < columnNames.Count)
{
StorageMappingItemLoader.AddToSchemaErrorWithMemberAndStructure(
Strings.Mapping_ModificationFunction_AmbiguousResultBinding,
property.Name, StringUtil.ToCommaSeparatedString(columnNames),
StorageMappingErrorCode.AmbiguousResultBindingInModificationFunctionMapping,
m_parentLoader.m_sourceLocation, xmlLineInfoNav,
m_parentLoader.m_parsingErrors);
return new List<StorageModificationFunctionResultBinding>();
}
}
return resultBindings;
}
// Loads parameter bindings from the given node, validating bindings:
// - All parameters are covered
// - Referenced names exist in type
// - Parameter and scalar type are compatible
// - Legal versions are given
private IEnumerable<StorageModificationFunctionParameterBinding> LoadParameterBindings(XPathNavigator nav, StructuralType type)
{
// recursively retrieve bindings (current member path is empty)
// immediately construct a list of bindings to force execution of the LoadParameterBindings
// yield method
List<StorageModificationFunctionParameterBinding> parameterBindings = new List<StorageModificationFunctionParameterBinding>(
LoadParameterBindings(nav.Clone(), type, restrictToKeyMembers: false));
// check that all parameters have been mapped
Set<FunctionParameter> unmappedParameters = new Set<FunctionParameter>(m_function.Parameters);
unmappedParameters.Subtract(m_seenParameters);
if (0 != unmappedParameters.Count)
{
AddToSchemaErrorWithMemberAndStructure(Strings.Mapping_ModificationFunction_MissingParameter,
m_function.FullName, StringUtil.ToCommaSeparatedString(unmappedParameters),
StorageMappingErrorCode.InvalidParameterInModificationFunctionMapping,
m_parentLoader.m_sourceLocation, (IXmlLineInfo)nav,
m_parentLoader.m_parsingErrors);
return new List<StorageModificationFunctionParameterBinding>();
}
return parameterBindings;
}
private IEnumerable<StorageModificationFunctionParameterBinding> LoadParameterBindings(XPathNavigator nav, StructuralType type,
bool restrictToKeyMembers)
{
// walk through all child bindings
if (nav.MoveToChild(XPathNodeType.Element))
{
do
{
switch (nav.LocalName)
{
case StorageMslConstructs.ScalarPropertyElement:
{
StorageModificationFunctionParameterBinding binding = LoadScalarPropertyParameterBinding(
nav.Clone(), type, restrictToKeyMembers);
if (binding != null)
{
yield return binding;
}
else
{
yield break;
}
}
break;
case StorageMslConstructs.ComplexPropertyElement:
{
ComplexType complexType;
EdmMember property = LoadComplexTypeProperty(
nav.Clone(), type, out complexType);
if (property != null)
{
// recursively retrieve mappings
m_members.Push(property);
foreach (StorageModificationFunctionParameterBinding binding in
LoadParameterBindings(nav.Clone(), complexType, restrictToKeyMembers))
{
yield return binding;
}
m_members.Pop();
}
}
break;
case StorageMslConstructs.AssociationEndElement:
{
AssociationSetEnd toEnd = LoadAssociationEnd(nav.Clone());
if (toEnd != null)
{
// translate the bindings for the association end
m_members.Push(toEnd.CorrespondingAssociationEndMember);
m_associationSetNavigation = toEnd.ParentAssociationSet;
foreach (StorageModificationFunctionParameterBinding binding in
LoadParameterBindings(nav.Clone(), toEnd.EntitySet.ElementType, true /* restrictToKeyMembers */))
{
yield return binding;
}
m_associationSetNavigation = null;
m_members.Pop();
}
}
break;
case StorageMslConstructs.EndPropertyMappingElement:
{
AssociationSetEnd end = LoadEndProperty(nav.Clone());
if (end != null)
{
// translate the bindings for the end property
m_members.Push(end.CorrespondingAssociationEndMember);
foreach (StorageModificationFunctionParameterBinding binding in
LoadParameterBindings(nav.Clone(), end.EntitySet.ElementType, true /* restrictToKeyMembers */))
{
yield return binding;
}
m_members.Pop();
}
}
break;
}
} while (nav.MoveToNext(XPathNodeType.Element));
}
}
private AssociationSetEnd LoadAssociationEnd(XPathNavigator nav)
{
IXmlLineInfo xmlLineInfoNav = (IXmlLineInfo)nav;
// retrieve element attributes
string associationSetName = m_parentLoader.GetAliasResolvedAttributeValue(
nav.Clone(), StorageMslConstructs.AssociationSetAttribute);
string fromRole = m_parentLoader.GetAliasResolvedAttributeValue(
nav.Clone(), StorageMslConstructs.FromAttribute);
string toRole = m_parentLoader.GetAliasResolvedAttributeValue(
nav.Clone(), StorageMslConstructs.ToAttribute);
// retrieve metadata
RelationshipSet relationshipSet = null;
AssociationSet associationSet;
// validate the association set exists
if (null == associationSetName ||
!m_modelContainer.TryGetRelationshipSetByName(associationSetName, false, out relationshipSet) ||
BuiltInTypeKind.AssociationSet != relationshipSet.BuiltInTypeKind)
{
StorageMappingItemLoader.AddToSchemaErrorsWithMemberInfo(
Strings.Mapping_ModificationFunction_AssociationSetDoesNotExist,
associationSetName, StorageMappingErrorCode.InvalidAssociationSet,
m_parentLoader.m_sourceLocation, xmlLineInfoNav,
m_parentLoader.m_parsingErrors);
return null;
}
associationSet = (AssociationSet)relationshipSet;
// validate the from end exists
AssociationSetEnd fromEnd = null;
if (null == fromRole ||
!associationSet.AssociationSetEnds.TryGetValue(fromRole, false, out fromEnd))
{
StorageMappingItemLoader.AddToSchemaErrorsWithMemberInfo(
Strings.Mapping_ModificationFunction_AssociationSetRoleDoesNotExist,
fromRole, StorageMappingErrorCode.InvalidAssociationSetRoleInModificationFunctionMapping,
m_parentLoader.m_sourceLocation, xmlLineInfoNav, m_parentLoader.m_parsingErrors);
return null;
}
// validate the to end exists
AssociationSetEnd toEnd = null;
if (null == toRole ||
!associationSet.AssociationSetEnds.TryGetValue(toRole, false, out toEnd))
{
StorageMappingItemLoader.AddToSchemaErrorsWithMemberInfo(
Strings.Mapping_ModificationFunction_AssociationSetRoleDoesNotExist,
toRole, StorageMappingErrorCode.InvalidAssociationSetRoleInModificationFunctionMapping,
m_parentLoader.m_sourceLocation, xmlLineInfoNav, m_parentLoader.m_parsingErrors);
return null;
}
// validate ends reference the current entity set
if (!fromEnd.EntitySet.Equals(m_entitySet))
{
StorageMappingItemLoader.AddToSchemaErrorsWithMemberInfo(
Strings.Mapping_ModificationFunction_AssociationSetFromRoleIsNotEntitySet,
fromRole, StorageMappingErrorCode.InvalidAssociationSetRoleInModificationFunctionMapping,
m_parentLoader.m_sourceLocation, xmlLineInfoNav, m_parentLoader.m_parsingErrors);
return null;
}
// validate cardinality of to end (can be at most one)
if (toEnd.CorrespondingAssociationEndMember.RelationshipMultiplicity != RelationshipMultiplicity.One &&
toEnd.CorrespondingAssociationEndMember.RelationshipMultiplicity != RelationshipMultiplicity.ZeroOrOne)
{
StorageMappingItemLoader.AddToSchemaErrorsWithMemberInfo(
Strings.Mapping_ModificationFunction_AssociationSetCardinality,
toRole, StorageMappingErrorCode.InvalidAssociationSetCardinalityInModificationFunctionMapping,
m_parentLoader.m_sourceLocation, xmlLineInfoNav, m_parentLoader.m_parsingErrors);
return null;
}
// if this is a FK, raise an error or a warning if the mapping would have been allowed in V1
// (all dependent properties are part of the primary key)
if (associationSet.ElementType.IsForeignKey)
{
ReferentialConstraint constraint = associationSet.ElementType.ReferentialConstraints.Single();
EdmSchemaError error = StorageMappingItemLoader.AddToSchemaErrorsWithMemberInfo(
Strings.Mapping_ModificationFunction_AssociationEndMappingForeignKeyAssociation,
toRole, StorageMappingErrorCode.InvalidModificationFunctionMappingAssociationEndForeignKey, m_parentLoader.m_sourceLocation,
xmlLineInfoNav, m_parentLoader.m_parsingErrors);
if (fromEnd.CorrespondingAssociationEndMember == constraint.ToRole &&
constraint.ToProperties.All(p => m_entitySet.ElementType.KeyMembers.Contains(p)))
{
// Just a warning...
error.Severity = EdmSchemaErrorSeverity.Warning;
}
else
{
return null;
}
}
return toEnd;
}
private AssociationSetEnd LoadEndProperty(XPathNavigator nav)
{
// retrieve element attributes
string role = m_parentLoader.GetAliasResolvedAttributeValue(
nav.Clone(), StorageMslConstructs.EndPropertyMappingNameAttribute);
// validate the role exists
AssociationSetEnd end = null;
if (null == role ||
!m_associationSet.AssociationSetEnds.TryGetValue(role, false, out end))
{
StorageMappingItemLoader.AddToSchemaErrorsWithMemberInfo(
Strings.Mapping_ModificationFunction_AssociationSetRoleDoesNotExist,
role, StorageMappingErrorCode.InvalidAssociationSetRoleInModificationFunctionMapping,
m_parentLoader.m_sourceLocation, (IXmlLineInfo)nav, m_parentLoader.m_parsingErrors);
return null;
}
return end;
}
private EdmMember LoadComplexTypeProperty(XPathNavigator nav, StructuralType type, out ComplexType complexType)
{
IXmlLineInfo xmlLineInfoNav = (IXmlLineInfo)nav;
// retrieve element attributes
string propertyName = m_parentLoader.GetAliasResolvedAttributeValue(
nav.Clone(), StorageMslConstructs.ComplexPropertyNameAttribute);
string typeName = m_parentLoader.GetAliasResolvedAttributeValue(
nav.Clone(), StorageMslConstructs.ComplexTypeMappingTypeNameAttribute);
// retrieve metadata
EdmMember property = null;
if (null == propertyName ||
!type.Members.TryGetValue(propertyName, false, out property))
{
// raise exception if the property does not exist
StorageMappingItemLoader.AddToSchemaErrorWithMemberAndStructure(
Strings.Mapping_ModificationFunction_PropertyNotFound,
propertyName, type.Name, StorageMappingErrorCode.InvalidEdmMember,
m_parentLoader.m_sourceLocation, xmlLineInfoNav, m_parentLoader.m_parsingErrors);
complexType = null;
return null;
}
complexType = null;
if (null == typeName ||
!m_edmItemCollection.TryGetItem<ComplexType>(typeName, out complexType))
{
// raise exception if the type does not exist
StorageMappingItemLoader.AddToSchemaErrorsWithMemberInfo(
Strings.Mapping_ModificationFunction_ComplexTypeNotFound,
typeName, StorageMappingErrorCode.InvalidComplexType,
m_parentLoader.m_sourceLocation, xmlLineInfoNav
, m_parentLoader.m_parsingErrors);
return null;
}
if (!property.TypeUsage.EdmType.Equals(complexType) &&
!Helper.IsSubtypeOf(property.TypeUsage.EdmType, complexType))
{
// raise exception if the complex type is incorrect
StorageMappingItemLoader.AddToSchemaErrorWithMemberAndStructure(
Strings.Mapping_ModificationFunction_WrongComplexType,
typeName, property.Name, StorageMappingErrorCode.InvalidComplexType,
m_parentLoader.m_sourceLocation, xmlLineInfoNav
, m_parentLoader.m_parsingErrors);
return null;
}
return property;
}
private StorageModificationFunctionParameterBinding LoadScalarPropertyParameterBinding(XPathNavigator nav, StructuralType type, bool restrictToKeyMembers)
{
IXmlLineInfo xmlLineInfoNav = (IXmlLineInfo)nav;
// get attribute values
string parameterName = m_parentLoader.GetAliasResolvedAttributeValue(nav.Clone(), StorageMslConstructs.ParameterNameAttribute);
string propertyName = m_parentLoader.GetAliasResolvedAttributeValue(nav.Clone(), StorageMslConstructs.ScalarPropertyNameAttribute);
string version = m_parentLoader.GetAliasResolvedAttributeValue(nav.Clone(), StorageMslConstructs.ParameterVersionAttribute);
// determine version
bool isCurrent = false;
if (null == version)
{
// use default
if (!m_allowOriginalVersion)
{
isCurrent = true;
}
else if (!m_allowCurrentVersion)
{
isCurrent = false;
}
else
{
// add a schema error and return as there is no default
StorageMappingItemLoader.AddToSchemaErrors(
Strings.Mapping_ModificationFunction_MissingVersion,
StorageMappingErrorCode.MissingVersionInModificationFunctionMapping, m_parentLoader.m_sourceLocation,
xmlLineInfoNav, m_parentLoader.m_parsingErrors);
return null;
}
}
else
{
// check the value given by the user
isCurrent = version == StorageMslConstructs.ParameterVersionAttributeCurrentValue;
}
if (isCurrent && !m_allowCurrentVersion)
{
//Add a schema error and return since the 'current' property version is not available
StorageMappingItemLoader.AddToSchemaErrors(
Strings.Mapping_ModificationFunction_VersionMustBeOriginal,
StorageMappingErrorCode.InvalidVersionInModificationFunctionMapping,
m_parentLoader.m_sourceLocation, xmlLineInfoNav
, m_parentLoader.m_parsingErrors);
return null;
}
if (!isCurrent && !m_allowOriginalVersion)
{
// Add a schema error and return since the 'original' property version is not available
StorageMappingItemLoader.AddToSchemaErrors(
Strings.Mapping_ModificationFunction_VersionMustBeCurrent,
StorageMappingErrorCode.InvalidVersionInModificationFunctionMapping,
m_parentLoader.m_sourceLocation, xmlLineInfoNav
, m_parentLoader.m_parsingErrors);
return null;
}
// retrieve metadata
FunctionParameter parameter = null;
if (null == parameterName ||
!m_function.Parameters.TryGetValue(parameterName, false, out parameter))
{
//Add a schema error and return if the parameter does not exist
StorageMappingItemLoader.AddToSchemaErrorWithMemberAndStructure(
Strings.Mapping_ModificationFunction_ParameterNotFound,
parameterName, m_function.Name,
StorageMappingErrorCode.InvalidParameterInModificationFunctionMapping,
m_parentLoader.m_sourceLocation, xmlLineInfoNav
, m_parentLoader.m_parsingErrors);
return null;
}
EdmMember property = null;
if (restrictToKeyMembers)
{
if (null == propertyName ||
!((EntityType)type).KeyMembers.TryGetValue(propertyName, false, out property))
{
// raise exception if the property does not exist
StorageMappingItemLoader.AddToSchemaErrorWithMemberAndStructure(
Strings.Mapping_ModificationFunction_PropertyNotKey,
propertyName, type.Name,
StorageMappingErrorCode.InvalidEdmMember,
m_parentLoader.m_sourceLocation, xmlLineInfoNav, m_parentLoader.m_parsingErrors);
return null;
}
}
else
{
if (null == propertyName ||
!type.Members.TryGetValue(propertyName, false, out property))
{
// raise exception if the property does not exist
StorageMappingItemLoader.AddToSchemaErrorWithMemberAndStructure(
Strings.Mapping_ModificationFunction_PropertyNotFound,
propertyName, type.Name,
StorageMappingErrorCode.InvalidEdmMember,
m_parentLoader.m_sourceLocation, xmlLineInfoNav, m_parentLoader.m_parsingErrors);
return null;
}
}
// check that the parameter hasn't already been seen
if (m_seenParameters.Contains(parameter))
{
StorageMappingItemLoader.AddToSchemaErrorsWithMemberInfo(
Strings.Mapping_ModificationFunction_ParameterBoundTwice,
parameterName, StorageMappingErrorCode.ParameterBoundTwiceInModificationFunctionMapping,
m_parentLoader.m_sourceLocation, xmlLineInfoNav, m_parentLoader.m_parsingErrors);
return null;
}
int errorCount = m_parentLoader.m_parsingErrors.Count;
TypeUsage mappedStoreType = Helper.ValidateAndConvertTypeUsage(property,
xmlLineInfoNav,
m_parentLoader.m_sourceLocation,
property.TypeUsage,
parameter.TypeUsage,
m_parentLoader.m_parsingErrors,
m_storeItemCollection);
// validate type compatibility
if (mappedStoreType == null && errorCount == m_parentLoader.m_parsingErrors.Count)
{
AddToSchemaErrorWithMessage(
Strings.Mapping_ModificationFunction_PropertyParameterTypeMismatch(
property.TypeUsage.EdmType,
property.Name,
property.DeclaringType.FullName,
parameter.TypeUsage.EdmType,
parameter.Name,
m_function.FullName),
StorageMappingErrorCode.InvalidModificationFunctionMappingPropertyParameterTypeMismatch,
m_parentLoader.m_sourceLocation,
xmlLineInfoNav,
m_parentLoader.m_parsingErrors);
}
// create the binding object
m_members.Push(property);
// if the member path includes a FK relationship, remap to the corresponding FK property
IEnumerable<EdmMember> members = m_members;
AssociationSet associationSetNavigation = m_associationSetNavigation;
if (m_members.Last().BuiltInTypeKind == BuiltInTypeKind.AssociationEndMember)
{
AssociationEndMember targetEnd = (AssociationEndMember)m_members.Last();
AssociationType associationType = (AssociationType)targetEnd.DeclaringType;
if (associationType.IsForeignKey)
{
ReferentialConstraint constraint = associationType.ReferentialConstraints.Single();
if (constraint.FromRole == targetEnd)
{
int ordinal = constraint.FromProperties.IndexOf((EdmProperty)m_members.First());
// rebind to the foreign key (no longer an association set navigation)
members = new EdmMember[] { constraint.ToProperties[ordinal], };
associationSetNavigation = null;
}
}
}
StorageModificationFunctionParameterBinding binding = new StorageModificationFunctionParameterBinding(parameter, new StorageModificationFunctionMemberPath(
members, associationSetNavigation), isCurrent);
m_members.Pop();
// remember that we've seen a binding for this parameter
m_seenParameters.Add(parameter);
return binding;
}
/// <summary>
/// Loads function metadata and ensures the function is supportable for function mapping.
/// </summary>
private EdmFunction LoadAndValidateFunctionMetadata(XPathNavigator nav, out FunctionParameter rowsAffectedParameter)
{
IXmlLineInfo xmlLineInfoNav = (IXmlLineInfo)nav;
// Different operations may be mapped to the same function (e.g. both INSERT and UPDATE are handled by a single
// UPSERT function). Between loading functions, we can clear the set of seen parameters, because we may see them
// again and don't want to claim there's a collision in such cases.
m_seenParameters.Clear();
// retrieve function attributes from the current element
string functionName = m_parentLoader.GetAliasResolvedAttributeValue(nav.Clone(), StorageMslConstructs.FunctionNameAttribute);
rowsAffectedParameter = null;
// find function metadata
System.Collections.ObjectModel.ReadOnlyCollection<EdmFunction> functionOverloads =
m_storeItemCollection.GetFunctions(functionName);
if (functionOverloads.Count == 0)
{
AddToSchemaErrorsWithMemberInfo(Strings.Mapping_ModificationFunction_UnknownFunction, functionName,
StorageMappingErrorCode.InvalidModificationFunctionMappingUnknownFunction, m_parentLoader.m_sourceLocation,
xmlLineInfoNav, m_parentLoader.m_parsingErrors);
return null;
}
if (1 < functionOverloads.Count)
{
AddToSchemaErrorsWithMemberInfo(Strings.Mapping_ModificationFunction_AmbiguousFunction, functionName,
StorageMappingErrorCode.InvalidModificationFunctionMappingAmbiguousFunction, m_parentLoader.m_sourceLocation,
xmlLineInfoNav, m_parentLoader.m_parsingErrors);
return null;
}
EdmFunction function = functionOverloads[0];
// check function is legal for function mapping
if (MetadataHelper.IsComposable(function))
{ // only non-composable functions are permitted
AddToSchemaErrorsWithMemberInfo(Strings.Mapping_ModificationFunction_NotValidFunction, functionName,
StorageMappingErrorCode.InvalidModificationFunctionMappingNotValidFunction, m_parentLoader.m_sourceLocation,
xmlLineInfoNav, m_parentLoader.m_parsingErrors);
return null;
}
// check for parameter
string rowsAffectedParameterName = GetAttributeValue(nav, StorageMslConstructs.RowsAffectedParameterAttribute);
if (!string.IsNullOrEmpty(rowsAffectedParameterName))
{
// check that the parameter exists
if (!function.Parameters.TryGetValue(rowsAffectedParameterName, false, out rowsAffectedParameter))
{
AddToSchemaErrorWithMessage(Strings.Mapping_FunctionImport_RowsAffectedParameterDoesNotExist(
rowsAffectedParameterName, function.FullName),
StorageMappingErrorCode.MappingFunctionImportRowsAffectedParameterDoesNotExist,
m_parentLoader.m_sourceLocation, xmlLineInfoNav, m_parentLoader.m_parsingErrors);
return null;
}
// check that the parameter is an out parameter
if (ParameterMode.Out != rowsAffectedParameter.Mode && ParameterMode.InOut != rowsAffectedParameter.Mode)
{
AddToSchemaErrorWithMessage(Strings.Mapping_FunctionImport_RowsAffectedParameterHasWrongMode(
rowsAffectedParameterName, rowsAffectedParameter.Mode, ParameterMode.Out, ParameterMode.InOut),
StorageMappingErrorCode.MappingFunctionImportRowsAffectedParameterHasWrongMode,
m_parentLoader.m_sourceLocation, xmlLineInfoNav, m_parentLoader.m_parsingErrors);
return null;
}
// check that the parameter type is an integer type
PrimitiveType rowsAffectedParameterType = (PrimitiveType)rowsAffectedParameter.TypeUsage.EdmType;
if (!TypeSemantics.IsIntegerNumericType(rowsAffectedParameter.TypeUsage))
{
AddToSchemaErrorWithMessage(Strings.Mapping_FunctionImport_RowsAffectedParameterHasWrongType(
rowsAffectedParameterName, rowsAffectedParameterType.PrimitiveTypeKind),
StorageMappingErrorCode.MappingFunctionImportRowsAffectedParameterHasWrongType,
m_parentLoader.m_sourceLocation, xmlLineInfoNav, m_parentLoader.m_parsingErrors);
return null;
}
m_seenParameters.Add(rowsAffectedParameter);
}
// check that all parameters are allowed
foreach (FunctionParameter parameter in function.Parameters)
{
if (ParameterMode.In != parameter.Mode && rowsAffectedParameterName != parameter.Name)
{ // rows affected is 'out' not 'in'
AddToSchemaErrorWithMessage(Strings.Mapping_ModificationFunction_NotValidFunctionParameter(functionName,
parameter.Name, StorageMslConstructs.RowsAffectedParameterAttribute), StorageMappingErrorCode.InvalidModificationFunctionMappingNotValidFunctionParameter,
m_parentLoader.m_sourceLocation, xmlLineInfoNav, m_parentLoader.m_parsingErrors);
return null;
}
}
return function;
}
}
#endregion
/// <summary>
/// Checks whether the <paramref name="typeUsage"/> represents a type usage for an enumeration type and if
/// this is the case creates a new type usage built using the underlying type of the enumeration type.
/// </summary>
/// <param name="typeUsage">TypeUsage to resolve.</param>
/// <returns>
/// If <paramref name="typeUsage"/> represents a TypeUsage for enumeration type the method returns a new
/// TypeUsage instance created using the underlying type of the enumeration type. Otherwise the method
/// returns <paramref name="typeUsage"/>.
/// </returns>
private static TypeUsage ResolveTypeUsageForEnums(TypeUsage typeUsage)
{
Debug.Assert(typeUsage != null, "typeUsage != null");
return Helper.IsEnumType(typeUsage.EdmType) ?
TypeUsage.Create(Helper.GetUnderlyingEdmTypeForEnumType(typeUsage.EdmType), typeUsage.Facets) :
typeUsage;
}
}
}
|