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
|
//---------------------------------------------------------------------
// <copyright file="EntityStoreSchemaGenerator.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//
// @owner [....]
// @backupOwner [....]
//---------------------------------------------------------------------
using System.Collections.Generic;
using System.Diagnostics;
using System.Xml;
using SOM=System.Data.EntityModel;
using System.Globalization;
using System.Data.Metadata.Edm;
using System.Data.Entity.Design.Common;
using System.Data.Entity.Design.SsdlGenerator;
using System.Data.Common;
using System.Data.EntityClient;
using System.IO;
using System.Data.Mapping;
using System.Data.Common.Utils;
using System.Collections.ObjectModel;
using System.Data.Common.CommandTrees;
using System.Data.Common.CommandTrees.ExpressionBuilder;
using System.Text;
using System.Linq;
using Microsoft.Build.Utilities;
namespace System.Data.Entity.Design
{
/// <summary>
/// Responsible for Loading Database Schema Information
/// </summary>
public sealed partial class EntityStoreSchemaGenerator
{
private const string CONTAINER_SUFFIX = "Container";
private EntityStoreSchemaGeneratorDatabaseSchemaLoader _loader;
private readonly string _provider;
private string _providerManifestToken = string.Empty;
private EntityContainer _entityContainer = null;
private StoreItemCollection _storeItemCollection;
private string _namespaceName;
private MetadataItemSerializer.ErrorsLookup _errorsLookup;
private List<EdmType> _invalidTypes;
private Version _targetEntityFrameworkVersion;
/// <summary>
/// Creates a new EntityStoreGenerator
/// </summary>
/// <param name="providerInvariantName">The name of the provider to use to load the schema information.</param>
/// <param name="connectionString">A connection string to the DB that should be loaded from.</param>
/// <param name="namespaceName">The namespace name to use for the store metadata that is generated.</param>
public EntityStoreSchemaGenerator(string providerInvariantName, string connectionString, string namespaceName)
{
EDesignUtil.CheckStringArgument(providerInvariantName, "providerInvariantName");
EDesignUtil.CheckArgumentNull(connectionString, "connectionString"); // check for NULL string and support empty connection string
EDesignUtil.CheckStringArgument(namespaceName, "namespaceName");
_namespaceName = namespaceName;
_provider = providerInvariantName;
_loader = new EntityStoreSchemaGeneratorDatabaseSchemaLoader(providerInvariantName, connectionString);
}
/// <summary>
/// Gets the EntityContainer that was created
/// </summary>
public EntityContainer EntityContainer
{
get
{
return _entityContainer;
}
}
/// <summary>
/// Gets the StoreItemCollection that was created
/// </summary>
[CLSCompliant(false)]
public StoreItemCollection StoreItemCollection
{
get
{
return _storeItemCollection;
}
}
/// <summary>
/// Indicates whether the given storage model will be used to produce an entity model with foreign keys.
/// </summary>
public bool GenerateForeignKeyProperties
{
get;
set;
}
/// <summary>
/// Creates a Metadata schema from the DbSchemaLoader that was passed in
/// </summary>
/// <returns>The new metadata for the schema that was loaded</returns>
public IList<EdmSchemaError> GenerateStoreMetadata()
{
List<EntityStoreSchemaFilterEntry> filters = new List<EntityStoreSchemaFilterEntry>();
return DoGenerateStoreMetadata(filters, EntityFrameworkVersions.Latest);
}
/// <summary>
/// Creates a Metadata schema from the DbSchemaLoader that was passed in
/// </summary>
/// <param name="filters">The filters to be applied during generation.</param>
/// <returns>The new metadata for the schema that was loaded</returns>
public IList<EdmSchemaError> GenerateStoreMetadata(IEnumerable<EntityStoreSchemaFilterEntry> filters)
{
EDesignUtil.CheckArgumentNull(filters, "filters");
return DoGenerateStoreMetadata(filters, EntityFrameworkVersions.Latest);
}
/// <summary>
/// Creates a Metadata schema from the DbSchemaLoader that was passed in
/// </summary>
/// <param name="filters">The filters to be applied during generation.</param>
/// <param name="targetFrameworkMoniker">The filters to be applied during generation.</param>
/// <returns>The new metadata for the schema that was loaded</returns>
public IList<EdmSchemaError> GenerateStoreMetadata(IEnumerable<EntityStoreSchemaFilterEntry> filters, Version targetEntityFrameworkVersion)
{
EDesignUtil.CheckArgumentNull(filters, "filters");
EDesignUtil.CheckTargetEntityFrameworkVersionArgument(targetEntityFrameworkVersion, "targetEntityFrameworkVersion");
// we are not going to actually use targetFrameworkMoniker at this time, but
// we want the option to use it in the future if we change the
// the ssdl schema
return DoGenerateStoreMetadata(filters, targetEntityFrameworkVersion);
}
private IList<EdmSchemaError> DoGenerateStoreMetadata(IEnumerable<EntityStoreSchemaFilterEntry> filters, Version targetEntityFrameworkVersion)
{
if (_entityContainer != null)
{
_entityContainer = null;
_storeItemCollection = null;
_errorsLookup = null;
_invalidTypes = null;
}
_targetEntityFrameworkVersion = targetEntityFrameworkVersion;
LoadMethodSessionState session = new LoadMethodSessionState(targetEntityFrameworkVersion);
try
{
_loader.Open();
DbConnection connection = _loader.InnerConnection;
DbProviderFactory providerFactory = DbProviderServices.GetProviderFactory(_loader.ProviderInvariantName);
DbProviderServices providerServices = DbProviderServices.GetProviderServices(providerFactory);
_providerManifestToken = providerServices.GetProviderManifestToken(connection);
DbProviderManifest storeManifest = providerServices.GetProviderManifest(_providerManifestToken);
session.Filters = filters;
Debug.Assert(_namespaceName != null, "_namespaceName should not be null at this point, did you add a new ctor?");
session.ItemCollection = new StoreItemCollection(providerFactory, providerServices.GetProviderManifest(_providerManifestToken), _providerManifestToken);
CreateTableEntityTypes(session);
CreateViewEntityTypes(session);
string entityContainerName = this._namespaceName.Replace(".", string.Empty) + CONTAINER_SUFFIX;
Debug.Assert(entityContainerName != null, "We should always have a container name");
EntityContainer entityContainer = new EntityContainer(entityContainerName, DataSpace.SSpace);
foreach (EntityType type in session.GetAllEntities())
{
Debug.Assert(type.KeyMembers.Count > 0, "Why do we have Entities without keys in our valid Entities collection");
session.ItemCollection.AddInternal(type);
EntitySet entitySet = CreateEntitySet(session, type);
session.EntityTypeToSet.Add(type, entitySet);
entityContainer.AddEntitySetBase(entitySet);
}
CreateAssociationTypes(session);
foreach (AssociationType type in session.AssociationTypes)
{
session.ItemCollection.AddInternal(type);
AssociationSet set = CreateAssociationSet(session, type);
entityContainer.AddEntitySetBase(set);
}
entityContainer.SetReadOnly();
session.ItemCollection.AddInternal(entityContainer);
FixupKeylessEntitySets(entityContainer, session);
if (_targetEntityFrameworkVersion >= EntityFrameworkVersions.Version3 &&
_loader.StoreSchemaModelVersion >= EntityFrameworkVersions.Version3)
{
CreateTvfReturnRowTypes(session);
}
CreateEdmFunctions(session);
foreach (EdmFunction function in session.Functions)
{
session.ItemCollection.AddInternal(function);
}
if (!HasErrorSeverityErrors(session.Errors))
{
_entityContainer = entityContainer;
_storeItemCollection = session.ItemCollection;
_errorsLookup = session.ItemToErrorsMap;
_invalidTypes = new List<EdmType>(session.InvalidTypes);
}
}
catch (Exception e)
{
if (MetadataUtil.IsCatchableExceptionType(e))
{
string message = EDesignUtil.GetMessagesFromEntireExceptionChain(e);
session.AddErrorsForType(null,
new EdmSchemaError(message,
(int)ModelBuilderErrorCode.UnknownError,
EdmSchemaErrorSeverity.Error,
e));
}
else
{
throw;
}
}
finally
{
_loader.Close();
}
return new List<EdmSchemaError>(session.Errors);
}
/// <summary>
/// Writes the Schema to xml
/// </summary>
/// <param name="outputFileName">The name of the file to write the xml to.</param>
public void WriteStoreSchema(string outputFileName)
{
EDesignUtil.CheckStringArgument(outputFileName, "outputFileName");
CheckValidItemCollection();
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
using (XmlWriter writer = XmlWriter.Create(outputFileName, settings))
{
WriteStoreSchema(writer);
}
}
/// <summary>
/// Writes the Schema to xml.
/// </summary>
/// <param name="writer">The XmlWriter to write the xml to.</param>
public void WriteStoreSchema(XmlWriter writer)
{
EDesignUtil.CheckArgumentNull(writer, "writer");
CheckValidItemCollection();
// we are going to add this EntityStoreSchemaGenerator namespace at the top of
// the file so that when we mark the entitysets with where they came from
// we don't have to repeat the namespace on each node. The VS tools use
// the source information to give better messages when refreshing the .ssdl from the db
// e.g.
// <Schema xmlns:store="http://schemas.microsoft.com/ado/2007/12/edm/EntityStoreSchemaGenerator ...>
// <EntityContainer ...>
// <!-- Views is the name of the StoreInformation EntitySet that this EntitySet was created from -->
// <EntitySet ... store:SchemaInformationSource="Views" />
// </EntityContainer>
// ...
// </Schema>
var xmlPrefixToNamespace = new KeyValuePair<string, string>("store", DesignXmlConstants.EntityStoreSchemaGeneratorNamespace);
MetadataItemSerializer.WriteXml(writer, StoreItemCollection, _namespaceName, _errorsLookup, _invalidTypes, _provider, _providerManifestToken, _targetEntityFrameworkVersion, xmlPrefixToNamespace);
}
/// <summary>
/// Creates an EntityConnection loaded with the providers metadata for the store schema.
/// Store schema model is the one used in <see cref="EntityFrameworkVersions.Version2"/>.
/// </summary>
/// <param name="providerInvariantName">The provider invariant name.</param>
/// <param name="connectionString">The connection for the providers connection.</param>
/// <returns>An EntityConnection that can query the ConceptualSchemaDefinition for the provider.</returns>
public static EntityConnection CreateStoreSchemaConnection(string providerInvariantName, string connectionString)
{
return CreateStoreSchemaConnection(providerInvariantName, connectionString, EntityFrameworkVersions.Version2);
}
/// <summary>
/// Creates an EntityConnection loaded with the providers metadata for the store schema.
/// Note that the targetEntityFrameworkVersion parameter uses internal EntityFramework version numbers as
/// described in the <see cref="EntityFrameworkVersions"/> class.
/// </summary>
/// <param name="providerInvariantName">The provider invariant name.</param>
/// <param name="connectionString">The connection for the providers connection.</param>
/// <param name="targetEntityFrameworkVersion">The internal Entity Framework version that is being targeted.</param>
/// <returns>An EntityConnection that can query the ConceptualSchemaDefinition for the provider.</returns>
public static EntityConnection CreateStoreSchemaConnection(string providerInvariantName, string connectionString, Version targetEntityFrameworkVersion)
{
EDesignUtil.CheckArgumentNull(providerInvariantName, "providerInvariantName");
EDesignUtil.CheckArgumentNull(connectionString, "connectionString");
EDesignUtil.CheckTargetEntityFrameworkVersionArgument(targetEntityFrameworkVersion, "targetEntityFrameworkVersion");
DbProviderFactory factory;
try
{
factory = DbProviderFactories.GetFactory(providerInvariantName);
}
catch (ArgumentException e)
{
throw EDesignUtil.Argument(Strings.EntityClient_InvalidStoreProvider(providerInvariantName), e);
}
DbProviderServices providerServices = MetadataUtil.GetProviderServices(factory);
DbConnection providerConnection = factory.CreateConnection();
if (providerConnection == null)
{
throw EDesignUtil.ProviderIncompatible(Strings.ProviderFactoryReturnedNullFactory(providerInvariantName));
}
providerConnection.ConnectionString = connectionString;
MetadataWorkspace workspace = GetProviderSchemaMetadataWorkspace(providerServices, providerConnection, targetEntityFrameworkVersion);
// create the connection with the information we have
return new EntityConnection(workspace, providerConnection);
}
private static MetadataWorkspace GetProviderSchemaMetadataWorkspace(DbProviderServices providerServices, DbConnection providerConnection, Version targetEntityFrameworkVersion)
{
XmlReader csdl = null;
XmlReader ssdl = null;
XmlReader msl = null;
Debug.Assert(EntityFrameworkVersions.IsValidVersion(targetEntityFrameworkVersion), "EntityFrameworkVersions.IsValidVersion(targetEntityFrameworkVersion)");
string csdlName;
string ssdlName;
string mslName;
if (targetEntityFrameworkVersion >= EntityFrameworkVersions.Version3)
{
csdlName = DbProviderManifest.ConceptualSchemaDefinitionVersion3;
ssdlName = DbProviderManifest.StoreSchemaDefinitionVersion3;
mslName = DbProviderManifest.StoreSchemaMappingVersion3;
}
else
{
csdlName = DbProviderManifest.ConceptualSchemaDefinition;
ssdlName = DbProviderManifest.StoreSchemaDefinition;
mslName = DbProviderManifest.StoreSchemaMapping;
}
try
{
// create the metadata workspace
MetadataWorkspace workspace = new MetadataWorkspace();
string manifestToken = providerServices.GetProviderManifestToken(providerConnection);
DbProviderManifest providerManifest = providerServices.GetProviderManifest(manifestToken);
// create the EdmItemCollection
IList<EdmSchemaError> errors;
ssdl = providerManifest.GetInformation(ssdlName);
string location = Strings.DbProviderServicesInformationLocationPath(providerConnection.GetType().Name, ssdlName);
List<string> ssdlLocations = new List<string>(1);
ssdlLocations.Add(location);
StoreItemCollection storeItemCollection = new StoreItemCollection(new XmlReader[] { ssdl }, ssdlLocations.AsReadOnly(), out errors);
ThrowOnError(errors);
workspace.RegisterItemCollection(storeItemCollection);
csdl = DbProviderServices.GetConceptualSchemaDefinition(csdlName);
location = Strings.DbProviderServicesInformationLocationPath(typeof(DbProviderServices).Name, csdlName);
List<string> csdlLocations = new List<string>(1);
csdlLocations.Add(location);
EdmItemCollection edmItemCollection = new EdmItemCollection(new XmlReader[] { csdl }, csdlLocations.AsReadOnly(), out errors);
ThrowOnError(errors);
workspace.RegisterItemCollection(edmItemCollection);
msl = providerManifest.GetInformation(mslName);
location = Strings.DbProviderServicesInformationLocationPath(providerConnection.GetType().Name, DbProviderManifest.StoreSchemaMapping);
List<string> mslLocations = new List<string>(1);
mslLocations.Add(location);
StorageMappingItemCollection mappingItemCollection = new StorageMappingItemCollection(edmItemCollection,
storeItemCollection,
new XmlReader[] { msl },
mslLocations,
out errors);
ThrowOnError(errors);
workspace.RegisterItemCollection(mappingItemCollection);
// make the views generate here so we can wrap the provider schema problems
// in a ProviderIncompatibleException
ForceViewGeneration(workspace);
return workspace;
}
catch (ProviderIncompatibleException)
{
// we don't really want to catch this one, just rethrow it
throw;
}
catch (Exception e)
{
if (MetadataUtil.IsCatchableExceptionType(e))
{
throw EDesignUtil.ProviderIncompatible(Strings.ProviderSchemaErrors, e);
}
throw;
}
finally
{
if (csdl != null) ((IDisposable)csdl).Dispose();
if (ssdl != null) ((IDisposable)ssdl).Dispose();
if (msl != null) ((IDisposable)msl).Dispose();
}
}
private static void ForceViewGeneration(MetadataWorkspace workspace)
{
ReadOnlyCollection<EntityContainer> containers = workspace.GetItems<EntityContainer>(DataSpace.SSpace);
Debug.Assert(containers.Count != 0, "no s space containers found");
Debug.Assert(containers[0].BaseEntitySets.Count != 0, "no entity sets in the sspace container");
workspace.GetCqtView(containers[0].BaseEntitySets[0]);
}
private static void ThrowOnError(IList<EdmSchemaError> errors)
{
if (errors.Count != 0)
{
if (!MetadataUtil.CheckIfAllErrorsAreWarnings(errors))
{
throw EDesignUtil.ProviderIncompatible(Strings.ProviderSchemaErrors, EntityUtil.InvalidSchemaEncountered(MetadataUtil.CombineErrorMessage(errors)));
}
}
}
private void CheckValidItemCollection()
{
if (_entityContainer == null)
{
throw EDesignUtil.EntityStoreGeneratorSchemaNotLoaded();
}
}
internal static bool HasErrorSeverityErrors(IEnumerable<EdmSchemaError> errors)
{
foreach (EdmSchemaError error in errors)
{
if (error.Severity == EdmSchemaErrorSeverity.Error)
{
return true;
}
}
return false;
}
private AssociationSet CreateAssociationSet(LoadMethodSessionState session,
AssociationType type)
{
AssociationSet set = new AssociationSet(type.Name, type);
foreach(AssociationEndMember end in type.RelationshipEndMembers)
{
EntitySet entitySet = session.GetEntitySet(end);
DbObjectKey key = session.GetKey(entitySet.ElementType);
AssociationSetEnd setEnd = new AssociationSetEnd(entitySet, set, end);
set.AddAssociationSetEnd(setEnd);
}
set.SetReadOnly();
return set;
}
private EntitySet CreateEntitySet(
LoadMethodSessionState session,
EntityType type
)
{
DbObjectKey key = session.GetKey(type);
string schema = key.Schema;
string table = null;
if (key.TableName != type.Name)
{
table = key.TableName;
}
EntitySet entitySet = new EntitySet(type.Name,
schema,
table,
null,
type);
MetadataProperty property = System.Data.EntityModel.SchemaObjectModel.SchemaElement.CreateMetadataPropertyFromOtherNamespaceXmlArtifact(DesignXmlConstants.EntityStoreSchemaGeneratorNamespace, DesignXmlConstants.EntityStoreSchemaGeneratorTypeAttributeName, GetSourceNameFromObjectType(key.ObjectType));
List<MetadataProperty> properties = new List<MetadataProperty>();
properties.Add(property);
entitySet.AddMetadataProperties(properties);
entitySet.SetReadOnly();
return entitySet;
}
private string GetSourceNameFromObjectType(DbObjectType dbObjectType)
{
switch(dbObjectType)
{
case DbObjectType.Table:
return DesignXmlConstants.TypeValueTables;
default:
Debug.Assert(dbObjectType == DbObjectType.View, "did you change to a call that could have different types?");
return DesignXmlConstants.TypeValueViews;
}
}
private void CreateEdmFunctions(LoadMethodSessionState session)
{
using(FunctionDetailsReader reader = _loader.LoadFunctionDetails(session.Filters))
{
DbObjectKey currentFunction = new DbObjectKey();
List<FunctionDetailsReader.Memento> parameters = new List<FunctionDetailsReader.Memento>();
while(reader.Read())
{
DbObjectKey rowFunction = reader.CreateDbObjectKey();
if (rowFunction != currentFunction)
{
if (!currentFunction.IsEmpty)
{
CreateEdmFunction(session, currentFunction, parameters);
parameters.Clear();
}
currentFunction = rowFunction;
}
parameters.Add(reader.CreateMemento());
}
if (parameters.Count != 0)
{
CreateEdmFunction(session, currentFunction, parameters);
}
}
}
private void CreateEdmFunction(LoadMethodSessionState session, DbObjectKey functionKey, List<FunctionDetailsReader.Memento> parameters)
{
Debug.Assert(parameters.Count != 0, "don't call the method with no data");
FunctionDetailsReader row = parameters[0].CreateReader();
FunctionParameter returnParameter = null;
bool isValid = true;
List<EdmSchemaError> errors = new List<EdmSchemaError>();
if (row.ReturnType != null)
{
Debug.Assert(!row.IsTvf, "TVF can't have ReturnType (used only for scalars).");
bool excludedForTarget;
TypeUsage returnType = GetScalarFunctionTypeUsage(session, row.ReturnType, out excludedForTarget);
if (returnType != null)
{
returnParameter = new FunctionParameter(EdmConstants.ReturnType, returnType, ParameterMode.ReturnValue);
}
else
{
isValid = false;
errors.Add(new EdmSchemaError(excludedForTarget ?
Strings.UnsupportedFunctionReturnDataTypeForTarget(row.ProcedureName, row.ReturnType) :
Strings.UnsupportedFunctionReturnDataType(row.ProcedureName, row.ReturnType),
(int)ModelBuilderErrorCode.UnsupportedType,
EdmSchemaErrorSeverity.Warning));
}
}
else if (row.IsTvf)
{
if (_targetEntityFrameworkVersion < EntityFrameworkVersions.Version3)
{
return;
}
RowType tvfReturnType;
if (session.TryGetTvfReturnType(functionKey, out tvfReturnType) && !session.InvalidTypes.Contains(tvfReturnType))
{
var collectionType = tvfReturnType.GetCollectionType();
collectionType.SetReadOnly();
returnParameter = new FunctionParameter(EdmConstants.ReturnType, TypeUsage.Create(collectionType), ParameterMode.ReturnValue);
}
else
{
isValid = false;
// If the TVF return type exists, but it is not valid, then reassign all its errors directly to the TVF.
// This is needed in order to avoid the following kind of error reporting:
// SSDL:
//
// <!-- Errors found while generating type:
// column1 type not supported
// column2 type not supported
// <RowType />
// -->
// ...
// ...
// <!-- Error found while generating type:
// TableReferencedByTvfWasNotFound
// <Function Name="TVF" .... />
// -->
//
// Instead we want something like this:
//
// <!-- Errors found while generating type:
// column1 type not supported
// column2 type not supported
// TableReferencedByTvfWasNotFound
// <Function Name="TVF" .... />
// -->
//
List<EdmSchemaError> tvfReturnTypeErrors;
if (tvfReturnType != null && session.ItemToErrorsMap.TryGetValue(tvfReturnType, out tvfReturnTypeErrors))
{
errors.AddRange(tvfReturnTypeErrors);
session.ItemToErrorsMap.Remove(tvfReturnType);
if (session.InvalidTypes.Contains(tvfReturnType))
{
session.InvalidTypes.Remove(tvfReturnType);
}
}
errors.Add(new EdmSchemaError(
Strings.TableReferencedByTvfWasNotFound(functionKey),
(int)ModelBuilderErrorCode.MissingTvfReturnTable,
EdmSchemaErrorSeverity.Warning));
}
}
bool caseSensitive = false;
UniqueIdentifierService uniqueIdentifiers = new UniqueIdentifierService(caseSensitive);
List<FunctionParameter> functionParameters = new List<FunctionParameter>();
for (int i = 0; i < parameters.Count && !row.IsParameterNameNull; i++)
{
row.Attach(parameters[i]);
TypeUsage parameterType = null;
bool excludedForTarget = false;
if (!row.IsParameterTypeNull)
{
parameterType = GetScalarFunctionTypeUsage(session, row.ParameterType, out excludedForTarget);
}
if (parameterType != null)
{
ParameterMode mode;
if (!row.TryGetParameterMode(out mode))
{
isValid = false;
string modeValue = "null";
if (!row.IsParameterModeNull)
{
modeValue = row.ProcParameterMode;
}
errors.Add(new EdmSchemaError(
Strings.ParameterDirectionNotValid(
row.ProcedureName,
row.ParameterName,
modeValue),
(int)ModelBuilderErrorCode.ParameterDirectionNotValid,
EdmSchemaErrorSeverity.Warning));
}
// the mode will get defaulted to something, so it is ok to keep creating after
// an error getting the mode value.
string parameterName = EntityModelSchemaGenerator.CreateValidEcmaName(row.ParameterName, 'p');
parameterName = uniqueIdentifiers.AdjustIdentifier(parameterName);
FunctionParameter parameter = new FunctionParameter(parameterName, parameterType, mode);
functionParameters.Add(parameter);
}
else
{
isValid = false;
string typeValue = "null";
if (!row.IsParameterTypeNull)
{
typeValue = row.ParameterType;
}
errors.Add(new EdmSchemaError(excludedForTarget ?
Strings.UnsupportedFunctionParameterDataTypeForTarget(row.ProcedureName, row.ParameterName, i, typeValue) :
Strings.UnsupportedFunctionParameterDataType(row.ProcedureName, row.ParameterName, i, typeValue),
(int)ModelBuilderErrorCode.UnsupportedType,
EdmSchemaErrorSeverity.Warning));
}
}
string functionName = EntityModelSchemaGenerator.CreateValidEcmaName(row.ProcedureName, 'f');
functionName = session.UsedTypeNames.AdjustIdentifier(functionName);
FunctionParameter[] returnParameters =
returnParameter == null ? new FunctionParameter[0] : new FunctionParameter[] {returnParameter};
EdmFunction function = new EdmFunction(functionName,
_namespaceName,
DataSpace.SSpace,
new EdmFunctionPayload
{
Schema = row.Schema,
StoreFunctionName = functionName != row.ProcedureName ? row.ProcedureName : null,
IsAggregate = row.IsIsAggregate,
IsBuiltIn = row.IsBuiltIn,
IsNiladic = row.IsNiladic,
IsComposable = row.IsComposable,
ReturnParameters = returnParameters,
Parameters = functionParameters.ToArray()
});
function.SetReadOnly();
session.AddErrorsForType(function, errors);
if (isValid)
{
session.Functions.Add(function);
}
else
{
session.InvalidTypes.Add(function);
}
}
private TypeUsage GetScalarFunctionTypeUsage(LoadMethodSessionState session, string dataType, out bool excludedForTarget)
{
PrimitiveType primitiveType;
if (session.TryGetStorePrimitiveType(dataType, out primitiveType, out excludedForTarget))
{
TypeUsage usage = TypeUsage.Create(primitiveType, FacetValues.NullFacetValues);
return usage;
}
return null;
}
private void CreateAssociationTypes(LoadMethodSessionState session)
{
string currentRelationshipId = string.Empty;
List<RelationshipDetailsRow> columns = new List<RelationshipDetailsRow>();
foreach (RelationshipDetailsRow row in _loader.LoadRelationships(session.Filters))
{
string rowRelationshipId = row.RelationshipId;
if (rowRelationshipId != currentRelationshipId)
{
if (!string.IsNullOrEmpty(currentRelationshipId))
{
CreateAssociationType(session, columns);
columns.Clear();
}
currentRelationshipId = rowRelationshipId;
}
columns.Add(row);
}
if (!string.IsNullOrEmpty(currentRelationshipId))
{
CreateAssociationType(session, columns);
}
}
private void CreateAssociationType(LoadMethodSessionState session,
List<RelationshipDetailsRow> columns)
{
Debug.Assert(columns.Count != 0, "should have at least one column");
RelationshipDetailsRow firstRow = columns[0];
// get the entity types for the ends
EntityType pkEntityType;
EntityType fkEntityType;
if (!TryGetEndEntities(session, firstRow, out pkEntityType, out fkEntityType))
{
return;
}
if (!AreRelationshipColumnsTheTypesEntireKey(pkEntityType, columns, r => r.PKColumn))
{
session.AddErrorsForType(pkEntityType, new EdmSchemaError(Strings.UnsupportedDbRelationship(firstRow.RelationshipName), (int)ModelBuilderErrorCode.UnsupportedDbRelationship, EdmSchemaErrorSeverity.Warning));
return;
}
UniqueIdentifierService usedEndNames = new UniqueIdentifierService(false);
// figure out the lower bound of the pk end
bool someFkColmnsAreNullable;
if (_targetEntityFrameworkVersion == EntityFrameworkVersions.Version1)
{
someFkColmnsAreNullable = AreAllFkKeyColumnsNullable(fkEntityType, columns);
}
else
{
someFkColmnsAreNullable = AreAnyFkKeyColumnsNullable(fkEntityType, columns);
}
RelationshipMultiplicity pkMultiplicity = someFkColmnsAreNullable ? RelationshipMultiplicity.ZeroOrOne : RelationshipMultiplicity.One;
//Get the Delete Action for the end and set it.
//The only DeleteAction we support is Cascade, ignor all others for now.
OperationAction onDeleteAction = OperationAction.None;
if (firstRow.RelationshipIsCascadeDelete)
{
onDeleteAction = OperationAction.Cascade;
}
AssociationEndMember pkEnd = CreateAssociationEnd( session,
pkEntityType,
pkMultiplicity,
usedEndNames, onDeleteAction);
RelationshipMultiplicity fkMultiplicity = RelationshipMultiplicity.Many;
if ( !someFkColmnsAreNullable &&
AreRelationshipColumnsTheTypesEntireKey(fkEntityType, columns, r => r.FKColumn))
{
// both the pk and fk side columns are the keys of their types
// so this is a 1 to one relationship
fkMultiplicity = RelationshipMultiplicity.ZeroOrOne;
}
AssociationEndMember fkEnd = CreateAssociationEnd(session,
fkEntityType,
fkMultiplicity,
usedEndNames, OperationAction.None);
// create the type
string typeName = session.UsedTypeNames.AdjustIdentifier(firstRow.RelationshipName);
AssociationType type = new AssociationType(typeName,
_namespaceName, false, DataSpace.SSpace);
type.AddMember(pkEnd);
type.AddMember(fkEnd);
List<EdmSchemaError> errors = new List<EdmSchemaError>();
bool isValid = CreateReferentialConstraint(session,
type,
pkEnd,
fkEnd,
columns,
errors);
string errorMessage;
// We can skip most validation checks if the FKs are directly surfaced (since we can produce valid mappings in these cases).
if (!this.GenerateForeignKeyProperties)
{
if (IsFkPartiallyContainedInPK(type, out errorMessage))
{
errors.Add(new EdmSchemaError(
errorMessage,
(int)ModelBuilderErrorCode.UnsupportedForeinKeyPattern,
EdmSchemaErrorSeverity.Warning));
isValid = false;
}
if (isValid)
{
//Now check if any FK (which could also be a PK) is shared among multiple Associations (ie shared via foreign key constraint).
// To do this we check if the Association Type being generated has any dependent property which is also a dependent in one of the association typed already added.
//If so, we keep one Association and throw the rest away.
foreach (var toPropertyOfAddedAssociation in session.AssociationTypes.SelectMany(t => t.ReferentialConstraints.SelectMany(refconst => refconst.ToProperties)))
{
foreach (var toProperty in type.ReferentialConstraints.SelectMany(refconst => refconst.ToProperties))
{
if (toProperty.DeclaringType.Equals(toPropertyOfAddedAssociation.DeclaringType) && toProperty.Equals(toPropertyOfAddedAssociation))
{
errors.Add(new EdmSchemaError(
Strings.SharedForeignKey(type.Name, toProperty, toProperty.DeclaringType),
(int)ModelBuilderErrorCode.SharedForeignKey,
EdmSchemaErrorSeverity.Warning));
isValid = false;
break;
}
}
if (!isValid)
{
break;
}
}
}
}
if (isValid)
{
session.AssociationTypes.Add(type);
}
else
{
session.InvalidTypes.Add(type);
session.RelationshipEndTypeLookup.Remove(pkEnd);
session.RelationshipEndTypeLookup.Remove(fkEnd);
}
type.SetReadOnly();
session.AddErrorsForType(type, errors);
}
private bool TryGetEndEntities(
LoadMethodSessionState session,
RelationshipDetailsRow row,
out EntityType pkEntityType,
out EntityType fkEntityType)
{
RelationshipDetailsCollection table = row.Table;
DbObjectKey pkKey = new DbObjectKey(row[table.PKCatalogColumn],
row[table.PKSchemaColumn],
row[table.PKTableColumn], DbObjectType.Unknown);
DbObjectKey fkKey = new DbObjectKey(row[table.FKCatalogColumn],
row[table.FKSchemaColumn],
row[table.FKTableColumn], DbObjectType.Unknown);
bool worked = session.TryGetEntity(pkKey, out pkEntityType);
worked &= session.TryGetEntity(fkKey, out fkEntityType);
return worked;
}
private static bool AreRelationshipColumnsTheTypesEntireKey(
EntityType entity,
List<RelationshipDetailsRow> columns,
Func<RelationshipDetailsRow, string> getColumnName)
{
if (entity.KeyMembers.Count != columns.Count)
{
// to be the entire key,
// must have the same number of columns
return false;
}
foreach (RelationshipDetailsRow row in columns)
{
if (!entity.KeyMembers.Contains(getColumnName(row)))
{
// not a key
return false;
}
}
return true;
}
private static bool AreAnyFkKeyColumnsNullable(
EntityType entity,
List<RelationshipDetailsRow> columns)
{
foreach (RelationshipDetailsRow row in columns)
{
EdmProperty property;
if (entity.Properties.TryGetValue(row.FKColumn, false, out property))
{
if (property.Nullable)
{
return true;
}
}
else
{
Debug.Fail("Why didn't we find the column?");
return false;
}
}
return false;
}
private static bool AreAllFkKeyColumnsNullable(
EntityType entity,
List<RelationshipDetailsRow> columns)
{
foreach (RelationshipDetailsRow row in columns)
{
EdmProperty property;
if (entity.Properties.TryGetValue(row.FKColumn, false, out property))
{
if (!property.Nullable)
{
return false;
}
}
else
{
Debug.Fail("Why didn't we find the column?");
return false;
}
}
return true;
}
private AssociationEndMember CreateAssociationEnd(LoadMethodSessionState session,
EntityType type,
RelationshipMultiplicity multiplicity,
UniqueIdentifierService usedEndNames,
OperationAction deleteAction
)
{
string role = usedEndNames.AdjustIdentifier(type.Name);
RefType refType = type.GetReferenceType();
AssociationEndMember end = new AssociationEndMember(role, refType, multiplicity);
end.DeleteBehavior = deleteAction;
session.RelationshipEndTypeLookup.Add(end, type);
return end;
}
private bool CreateReferentialConstraint(LoadMethodSessionState session,
AssociationType association,
AssociationEndMember pkEnd,
AssociationEndMember fkEnd,
List<RelationshipDetailsRow> columns,
List<EdmSchemaError> errors)
{
EdmProperty[] fromProperties = new EdmProperty[columns.Count];
EdmProperty[] toProperties = new EdmProperty[columns.Count];
EntityType pkEntityType = session.RelationshipEndTypeLookup[pkEnd];
EntityType fkEntityType = session.RelationshipEndTypeLookup[fkEnd];
for (int index = 0; index < columns.Count; index++)
{
EdmProperty property;
if(!pkEntityType.Properties.TryGetValue(columns[index].PKColumn, false, out property))
{
errors.Add(
new EdmSchemaError(
Strings.AssociationMissingKeyColumn(
pkEntityType.Name,
fkEntityType.Name,
pkEntityType.Name + "." + columns[index].PKColumn),
(int)ModelBuilderErrorCode.AssociationMissingKeyColumn,
EdmSchemaErrorSeverity.Warning));
return false;
}
fromProperties[index] = property;
if(!fkEntityType.Properties.TryGetValue(columns[index].FKColumn, false, out property))
{
errors.Add(
new EdmSchemaError(
Strings.AssociationMissingKeyColumn(
pkEntityType.Name,
fkEntityType.Name,
fkEntityType.Name + "." + columns[index].FKColumn),
(int)ModelBuilderErrorCode.AssociationMissingKeyColumn,
EdmSchemaErrorSeverity.Warning));
return false;
}
toProperties[index] = property;
}
ReferentialConstraint constraint = new ReferentialConstraint(pkEnd,
fkEnd,
fromProperties,
toProperties);
association.AddReferentialConstraint(constraint);
return true;
}
static internal bool IsFkPartiallyContainedInPK(AssociationType association, out string errorMessage)
{
ReferentialConstraint constraint = association.ReferentialConstraints[0];
EntityType toType = (EntityType)constraint.ToProperties[0].DeclaringType;
bool toPropertiesAreFullyContainedInPk = true;
bool toPropertiesContainedAtLeastOnePK = false;
foreach (EdmProperty edmProperty in constraint.ToProperties)
{
// check if there is at least one to property is not primary key
toPropertiesAreFullyContainedInPk &= toType.KeyMembers.Contains(edmProperty);
// check if there is one to property is primary key
toPropertiesContainedAtLeastOnePK |= toType.KeyMembers.Contains(edmProperty);
}
if (!toPropertiesAreFullyContainedInPk && toPropertiesContainedAtLeastOnePK)
{
string foreignKeys = MetadataUtil.MembersToCommaSeparatedString((System.Collections.IEnumerable)constraint.ToProperties);
string primaryKeys = MetadataUtil.MembersToCommaSeparatedString((System.Collections.IEnumerable)toType.KeyMembers);
errorMessage = Strings.UnsupportedForeignKeyPattern(association.Name, foreignKeys, primaryKeys, toType.Name);
return true;
}
errorMessage = "";
return false;
}
private void CreateViewEntityTypes(LoadMethodSessionState session)
{
CreateTableTypes(session, _loader.LoadViewDetails(session.Filters), CreateEntityType, DbObjectType.View);
}
private void CreateTableEntityTypes(LoadMethodSessionState session)
{
CreateTableTypes(session, _loader.LoadTableDetails(session.Filters), CreateEntityType, DbObjectType.Table);
}
private void CreateTvfReturnRowTypes(LoadMethodSessionState session)
{
CreateTableTypes(session, _loader.LoadFunctionReturnTableDetails(session.Filters), CreateTvfReturnRowType, DbObjectType.Function);
}
private void CreateTableTypes(
LoadMethodSessionState session,
IEnumerable<DataRow> tableDetailsRows,
Action<
LoadMethodSessionState/*session*/,
IList<TableDetailsRow>/*columns*/,
ICollection<string>/*primaryKeys*/,
DbObjectType/*objectType*/,
List<EdmSchemaError>/*errors*/> createType,
DbObjectType objectType)
{
DbObjectKey currentKey = new DbObjectKey();
List<TableDetailsRow> singleTableColumns = new List<TableDetailsRow>();
List<string> primaryKeys = new List<string>();
foreach (TableDetailsRow row in tableDetailsRows)
{
DbObjectKey rowKey = row.CreateDbObjectKey(objectType);
if (rowKey != currentKey)
{
if (singleTableColumns.Count != 0)
{
createType(
session,
singleTableColumns,
primaryKeys,
objectType,
null);
singleTableColumns.Clear();
primaryKeys.Clear();
}
currentKey = rowKey;
}
singleTableColumns.Add(row);
if (row.IsPrimaryKey)
{
primaryKeys.Add(row.ColumnName);
}
}
// pick up the last one
if (singleTableColumns.Count != 0)
{
createType(
session,
singleTableColumns,
primaryKeys,
objectType,
null);
}
}
private void CreateEntityType(
LoadMethodSessionState session,
IList<TableDetailsRow> columns,
ICollection<string> primaryKeys,
DbObjectType objectType,
List<EdmSchemaError> errors)
{
Debug.Assert(columns.Count != 0, "Trying to create an EntityType with 0 properties");
Debug.Assert(primaryKeys != null, "primaryKeys != null");
DbObjectKey tableKey = columns[0].CreateDbObjectKey(objectType);
if (errors == null)
{
errors = new List<EdmSchemaError>();
}
//
// Handle Tables without explicit declaration of keys
//
EntityCreationStatus status = EntityCreationStatus.Normal;
if (primaryKeys.Count == 0)
{
List<string> pKeys = new List<string>(columns.Count);
session.AddTableWithoutKey(tableKey);
if (InferKeyColumns(session, columns, pKeys, tableKey, ref primaryKeys))
{
errors.Add(new EdmSchemaError(
Strings.NoPrimaryKeyDefined(tableKey),
(int)ModelBuilderErrorCode.NoPrimaryKeyDefined,
EdmSchemaErrorSeverity.Warning));
status = EntityCreationStatus.ReadOnly;
}
else
{
errors.Add(new EdmSchemaError(
Strings.CannotCreateEntityWithNoPrimaryKeyDefined(tableKey),
(int)ModelBuilderErrorCode.CannotCreateEntityWithoutPrimaryKey,
EdmSchemaErrorSeverity.Warning));
status = EntityCreationStatus.Invalid;
}
}
Debug.Assert(primaryKeys == null || primaryKeys.Count > 0,"There must be at least one key columns at this point in time");
IList<string> excludedColumns;
var properties = CreateEdmProperties(session, columns, tableKey, errors, out excludedColumns);
var excludedKeyColumns = (primaryKeys != null ? primaryKeys.Intersect(excludedColumns) : new string[0]).ToArray();
if (primaryKeys != null && excludedKeyColumns.Length == 0)
{
foreach (EdmMember pkColumn in properties.Where(p => primaryKeys.Contains(p.Name)))
{
if (!MetadataUtil.IsValidKeyType(_targetEntityFrameworkVersion, pkColumn.TypeUsage.EdmType))
{
// make it a read-only table by calling this method recursively with no keys
errors = new List<EdmSchemaError>();
var tableColumn = columns.Where(c => c.ColumnName == pkColumn.Name).Single();
errors.Add(new EdmSchemaError(Strings.InvalidTypeForPrimaryKey(tableColumn.GetMostQualifiedTableName(),
tableColumn.ColumnName,
tableColumn.DataType),
(int)ModelBuilderErrorCode.InvalidKeyTypeFound,
EdmSchemaErrorSeverity.Warning));
string[] keyColumns = new string[0];
CreateEntityType(session, columns, keyColumns, objectType, errors);
return;
}
}
}
if (excludedKeyColumns.Length > 0)
{
// see if we have any keys left
if (primaryKeys != null && excludedKeyColumns.Length < primaryKeys.Count)
{
primaryKeys = primaryKeys.Except(excludedKeyColumns).ToList();
status = EntityCreationStatus.ReadOnly;
}
else
{
primaryKeys = null;
status = EntityCreationStatus.Invalid;
}
foreach (string columnName in excludedKeyColumns)
{
if (status == EntityCreationStatus.ReadOnly)
{
errors.Add(new EdmSchemaError(
Strings.ExcludedColumnWasAKeyColumnEntityIsReadOnly(columnName, columns[0].GetMostQualifiedTableName()),
(int)ModelBuilderErrorCode.ExcludedColumnWasAKeyColumn,
EdmSchemaErrorSeverity.Warning));
}
else
{
Debug.Assert(status == EntityCreationStatus.Invalid, "Did we change some code above to make it possible to be something different?");
errors.Add(new EdmSchemaError(
Strings.ExcludedColumnWasAKeyColumnEntityIsInvalid(columnName, columns[0].GetMostQualifiedTableName()),
(int)ModelBuilderErrorCode.ExcludedColumnWasAKeyColumn,
EdmSchemaErrorSeverity.Warning));
}
}
}
string typeName = session.UsedTypeNames.AdjustIdentifier(columns[0].TableName);
var entityType = new EntityType(typeName, _namespaceName, DataSpace.SSpace, primaryKeys, properties);
entityType.SetReadOnly();
switch (status)
{
case EntityCreationStatus.Normal:
session.AddEntity(tableKey, entityType);
break;
case EntityCreationStatus.ReadOnly:
session.AddEntity(tableKey, entityType);
session.ReadOnlyEntities.Add(entityType);
break;
default:
Debug.Assert(status == EntityCreationStatus.Invalid, "did you add a new value?");
session.InvalidTypes.Add(entityType);
break;
}
session.AddErrorsForType(entityType, errors);
}
private void CreateTvfReturnRowType(
LoadMethodSessionState session,
IList<TableDetailsRow> columns,
ICollection<string> primaryKeys,
DbObjectType objectType,
List<EdmSchemaError> errors)
{
Debug.Assert(columns.Count != 0, "Trying to create a RowType with 0 properties");
Debug.Assert(primaryKeys != null, "primaryKeys != null");
DbObjectKey tableKey = columns[0].CreateDbObjectKey(objectType);
if (errors == null)
{
errors = new List<EdmSchemaError>();
}
IList<string> excludedColumns;
var properties = CreateEdmProperties(session, columns, tableKey, errors, out excludedColumns);
var rowType = new RowType(properties);
rowType.SetReadOnly();
session.AddTvfReturnType(tableKey, rowType);
if (rowType.Properties.Count == 0)
{
session.InvalidTypes.Add(rowType);
}
session.AddErrorsForType(rowType, errors);
}
private IList<EdmProperty> CreateEdmProperties(
LoadMethodSessionState session,
IList<TableDetailsRow> columns,
DbObjectKey tableKey,
List<EdmSchemaError> errors,
out IList<string> excludedColumns)
{
Debug.Assert(columns.Count != 0, "columns.Count != 0");
Debug.Assert(errors != null, "errors != null");
var members = new List<EdmProperty>();
excludedColumns = new List<string>();
foreach (TableDetailsRow row in columns)
{
PrimitiveType primitiveType;
bool excludedForTarget = false;
if (row.IsDataTypeNull() || !session.TryGetStorePrimitiveType(row.DataType, out primitiveType, out excludedForTarget))
{
string message;
if (!row.IsDataTypeNull())
{
message = excludedForTarget ?
Strings.UnsupportedDataTypeForTarget(row.DataType, row.GetMostQualifiedTableName(), row.ColumnName) :
Strings.UnsupportedDataType(row.DataType, row.GetMostQualifiedTableName(), row.ColumnName);
}
else
{
message = Strings.UnsupportedDataTypeUnknownType(row.ColumnName, row.GetMostQualifiedTableName());
}
errors.Add(new EdmSchemaError(message, (int)ModelBuilderErrorCode.UnsupportedType, EdmSchemaErrorSeverity.Warning));
excludedColumns.Add(row.ColumnName);
continue;
}
Dictionary<string, Facet> facets = primitiveType.GetAssociatedFacetDescriptions().ToDictionary(fd => fd.FacetName, fd => fd.DefaultValueFacet);
facets[DbProviderManifest.NullableFacetName] = Facet.Create(facets[DbProviderManifest.NullableFacetName].Description, row.IsNullable);
if (primitiveType.PrimitiveTypeKind == PrimitiveTypeKind.Decimal)
{
Facet precision;
if (facets.TryGetValue(DbProviderManifest.PrecisionFacetName, out precision))
{
if (!row.IsPrecisionNull() && !precision.Description.IsConstant)
{
if (row.Precision < precision.Description.MinValue || row.Precision > precision.Description.MaxValue)
{
DbObjectKey key = row.CreateDbObjectKey(tableKey.ObjectType);
errors.Add(new EdmSchemaError(
Strings.ColumnFacetValueOutOfRange(
DbProviderManifest.PrecisionFacetName,
row.Precision,
precision.Description.MinValue,
precision.Description.MaxValue,
row.ColumnName,
key),
(int)ModelBuilderErrorCode.FacetValueOutOfRange,
EdmSchemaErrorSeverity.Warning));
excludedColumns.Add(row.ColumnName);
continue;
}
facets[precision.Name] = Facet.Create(precision.Description, (byte)row.Precision);
}
}
Facet scale;
if (facets.TryGetValue(DbProviderManifest.ScaleFacetName, out scale))
{
if (!row.IsScaleNull() && !scale.Description.IsConstant)
{
if (row.Scale < scale.Description.MinValue || row.Scale > scale.Description.MaxValue)
{
DbObjectKey key = row.CreateDbObjectKey(tableKey.ObjectType);
errors.Add(new EdmSchemaError(
Strings.ColumnFacetValueOutOfRange(
DbProviderManifest.ScaleFacetName,
row.Scale,
scale.Description.MinValue,
scale.Description.MaxValue,
row.ColumnName,
key),
(int)ModelBuilderErrorCode.FacetValueOutOfRange,
EdmSchemaErrorSeverity.Warning));
excludedColumns.Add(row.ColumnName);
continue;
}
facets[scale.Name] = Facet.Create(scale.Description, (byte)row.Scale);
}
}
}
else if (primitiveType.PrimitiveTypeKind == PrimitiveTypeKind.DateTime ||
primitiveType.PrimitiveTypeKind == PrimitiveTypeKind.Time ||
primitiveType.PrimitiveTypeKind == PrimitiveTypeKind.DateTimeOffset)
{
Facet datetimePrecision;
if (facets.TryGetValue(DbProviderManifest.PrecisionFacetName, out datetimePrecision))
{
if (!row.IsDateTimePrecisionNull() && !datetimePrecision.Description.IsConstant)
{
if (row.DateTimePrecision < datetimePrecision.Description.MinValue || row.DateTimePrecision > datetimePrecision.Description.MaxValue)
{
DbObjectKey key = row.CreateDbObjectKey(tableKey.ObjectType);
errors.Add(new EdmSchemaError(
Strings.ColumnFacetValueOutOfRange(
DbProviderManifest.PrecisionFacetName,
row.DateTimePrecision,
datetimePrecision.Description.MinValue,
datetimePrecision.Description.MaxValue,
row.ColumnName,
key),
(int)ModelBuilderErrorCode.FacetValueOutOfRange,
EdmSchemaErrorSeverity.Warning));
excludedColumns.Add(row.ColumnName);
continue;
}
facets[datetimePrecision.Name] = Facet.Create(datetimePrecision.Description, (byte)row.DateTimePrecision);
}
}
}
else if (primitiveType.PrimitiveTypeKind == PrimitiveTypeKind.String ||
primitiveType.PrimitiveTypeKind == PrimitiveTypeKind.Binary)
{
Facet maxLength;
if (facets.TryGetValue(DbProviderManifest.MaxLengthFacetName, out maxLength))
{
if (!row.IsMaximumLengthNull() && !maxLength.Description.IsConstant)
{
if (row.MaximumLength < maxLength.Description.MinValue || row.MaximumLength > maxLength.Description.MaxValue)
{
DbObjectKey key = row.CreateDbObjectKey(tableKey.ObjectType);
errors.Add(new EdmSchemaError(
Strings.ColumnFacetValueOutOfRange(
DbProviderManifest.MaxLengthFacetName,
row.MaximumLength,
maxLength.Description.MinValue,
maxLength.Description.MaxValue,
row.ColumnName,
key),
(int)ModelBuilderErrorCode.FacetValueOutOfRange,
EdmSchemaErrorSeverity.Warning));
excludedColumns.Add(row.ColumnName);
continue;
}
facets[maxLength.Name] = Facet.Create(maxLength.Description, row.MaximumLength);
}
}
}
if (!row.IsIsIdentityNull() && row.IsIdentity)
{
Facet facet = Facet.Create(System.Data.Metadata.Edm.Converter.StoreGeneratedPatternFacet, StoreGeneratedPattern.Identity);
facets.Add(facet.Name, facet);
}
else if (!row.IsIsServerGeneratedNull() && row.IsServerGenerated)
{
Facet facet = Facet.Create(System.Data.Metadata.Edm.Converter.StoreGeneratedPatternFacet, StoreGeneratedPattern.Computed);
facets.Add(facet.Name, facet);
}
members.Add(new EdmProperty(row.ColumnName, TypeUsage.Create(primitiveType, facets.Values)));
}
return members;
}
private bool InferKeyColumns(LoadMethodSessionState session, IList<TableDetailsRow> columns, List<string> pKeys, DbObjectKey tableKey, ref ICollection<string> primaryKeys)
{
for (int i = 0; i < columns.Count; i++)
{
if (!columns[i].IsNullable)
{
PrimitiveType primitiveType;
bool _;
if (session.TryGetStorePrimitiveType(columns[i].DataType, out primitiveType, out _) &&
MetadataUtil.IsValidKeyType(_targetEntityFrameworkVersion, primitiveType))
{
pKeys.Add(columns[i].ColumnName);
}
}
}
// if there are valid key column candidates, make them the new key columns
if (pKeys.Count > 0)
{
primaryKeys = pKeys;
}
else
{
primaryKeys = null;
}
return primaryKeys != null;
}
/// <summary>
/// Populates DefiningQuery attribute of RO view entities
/// </summary>
/// <param name="viewEntitySets"></param>
/// <param name="entityContainer"></param>
/// <param name="session"></param>
private void FixupKeylessEntitySets(EntityContainer entityContainer, LoadMethodSessionState session)
{
// if there are views to process
if (session.ReadOnlyEntities.Count > 0)
{
//
// create 'bogus' metadataworkspace
//
MetadataWorkspace metadataWorkspace = CreateMetadataWorkspace(entityContainer, session);
if (null == metadataWorkspace)
{
// failed to create bogus metadataworkspace
return;
}
//
// For all tables/views that we could infer valid keys, update DefiningQuery with
// provider specific ReadOnly view SQL
//
foreach (EntityType entityType in session.ReadOnlyEntities)
{
EntitySet entitySet = session.EntityTypeToSet[entityType];
DbObjectKey key = session.GetKey(entityType);
// add properties that make it possible for the designer to track back these
// types to their source db objects
List<MetadataProperty> properties = new List<MetadataProperty>();
if (key.Schema != null)
{
properties.Add(System.Data.EntityModel.SchemaObjectModel.SchemaElement.CreateMetadataPropertyFromOtherNamespaceXmlArtifact(DesignXmlConstants.EntityStoreSchemaGeneratorNamespace, DesignXmlConstants.EntityStoreSchemaGeneratorSchemaAttributeName, key.Schema));
}
properties.Add(System.Data.EntityModel.SchemaObjectModel.SchemaElement.CreateMetadataPropertyFromOtherNamespaceXmlArtifact(DesignXmlConstants.EntityStoreSchemaGeneratorNamespace, DesignXmlConstants.EntityStoreSchemaGeneratorNameAttributeName, key.TableName));
entitySet.AddMetadataProperties(properties);
FixupViewEntitySetDefiningQuery(entitySet, metadataWorkspace);
}
}
}
/// <summary>
/// Creates 'transient' metadataworkspace based on store schema (EntityContainer) and trivial C-S mapping
/// </summary>
/// <param name="entityContainer"></param>
/// <param name="session"></param>
/// <returns></returns>
private MetadataWorkspace CreateMetadataWorkspace(EntityContainer entityContainer, LoadMethodSessionState session)
{
MetadataWorkspace metadataWorkspace = new MetadataWorkspace();
EntityModelSchemaGenerator modelGen = new EntityModelSchemaGenerator(entityContainer);
modelGen.GenerateForeignKeyProperties = this.GenerateForeignKeyProperties;
IEnumerable<EdmSchemaError> errors = modelGen.GenerateMetadata();
if (EntityStoreSchemaGenerator.HasErrorSeverityErrors(errors))
{
// this is a 'transient' metadataworkspace
// no errors from this metadataworkspace should be shown to the user
return null;
}
// register edmitemcollection
metadataWorkspace.RegisterItemCollection(modelGen.EdmItemCollection);
// register StoreItemCollection
metadataWorkspace.RegisterItemCollection(session.ItemCollection);
// register mapping
using (MemoryStream memStream = new MemoryStream())
{
using (XmlWriter xmlWriter = XmlWriter.Create(memStream))
{
modelGen.WriteStorageMapping(xmlWriter);
xmlWriter.Close();
}
memStream.Seek(0, SeekOrigin.Begin);
using (XmlReader xmlReader = XmlReader.Create(memStream))
{
List<XmlReader> xmlReaders = new List<XmlReader>();
xmlReaders.Add(xmlReader);
metadataWorkspace.RegisterItemCollection(new StorageMappingItemCollection(modelGen.EdmItemCollection,
session.ItemCollection,
xmlReaders));
}
}
return metadataWorkspace;
}
/// <summary>
/// Generates provider specific, read only SQL and updates entitySet DefiningQuery
/// </summary>
/// <param name="entitySet"></param>
/// <param name="metadataWorkspace"></param>
private void FixupViewEntitySetDefiningQuery(EntitySet entitySet, MetadataWorkspace metadataWorkspace)
{
DbExpressionBinding inputBinding = DbExpressionBuilder.BindAs(DbExpressionBuilder.Scan(entitySet), entitySet.Name);
List<KeyValuePair<string, DbExpression>> projectList = new List<KeyValuePair<string, DbExpression>>(entitySet.ElementType.Members.Count);
foreach (EdmMember member in entitySet.ElementType.Members)
{
Debug.Assert(member.BuiltInTypeKind == BuiltInTypeKind.EdmProperty, "Every member must be a edmproperty");
EdmProperty propertyInfo = (EdmProperty)member;
projectList.Add(new KeyValuePair<string, DbExpression>(member.Name,
DbExpressionBuilder.Property(inputBinding.Variable, propertyInfo)));
}
DbExpression query = inputBinding.Project(DbExpressionBuilder.NewRow(projectList));
DbQueryCommandTree dbCommandTree = new DbQueryCommandTree(metadataWorkspace, DataSpace.SSpace, query);
//
// get provider SQL and set entitySet DefiningQuery
//
entitySet.DefiningQuery = (DbProviderServices.GetProviderServices(_loader.EntityConnection.StoreProviderFactory)
.CreateCommandDefinition(dbCommandTree))
.CreateCommand().CommandText;
Debug.Assert(!String.IsNullOrEmpty(entitySet.DefiningQuery), "DefiningQuery must not be null or empty");
}
}
}
|