From 86a1bcd467460ad445bbee649dc30783a46b672b Mon Sep 17 00:00:00 2001 From: David V <4495790+Opzet@users.noreply.github.com> Date: Thu, 25 Nov 2021 22:48:04 +0800 Subject: [PATCH] Master (#310) * Created an EF6 winform example * Working on example * Relocated examples to correect directory * Try 2 restructure * changed the string limit from 2 to 25 * WIP * WIP * Working Example 3: Need to implement How do you do for more fields? Like ISBN TO DO? // AuthorIA.Books..ISBN = "9780008277819"; * One to one isnt working?? * Cannot figure out how dto do child tables? * Working on Invoice EXample.. .argh * WIP- Course Manager Example * WIP - Annotations and commenting of issues * WIP Ex6 - Course Manager Student CRUD Completed Course CRUD pending Enrolment CRUD pending * Add Pk , make FK addressId Fixed one 2 one * Ex6 Course Stuck.. : How do you add enrollments? Line 348 FrmCourseManager * To Do FrmCourseManager: Line 348 I dont know how to create an enrolment? * Ex 6 Working ToDO Added Delete and update to enrolments * How do you find rows for courses? //To Do - look u p EF Message: SELECT 1 AS [C1], [Extent1].[EnrollmentId] AS [EnrollmentId], [Extent1].[Grade] AS [Grade], [Extent1].[CourseEnrollmentsCourseId] AS [CourseEnrollmentsCourseId], [Extent1].[StudentEnrollmentsStudentId] AS [StudentEnrollmentsStudentId] FROM [dbo].[Enrollments] AS [Extent1] */ // Student student = db.Students.First(s => s.StudentId == e.StudentEnrollmentsStudentId); // Course course = db.Courses.First(c => c.CourseId == e.CourseEnrollmentsCourseId); * How do you get linked tables? FrmCourseManager Line 460 * Cloned code over from https://github.com/Opzet/EFDesignerExamples Examples 1,2,3,4 & 6 working Pending pull request into https://github.com/msawczyn/EFDesigner * Working Examples with auto localdb Instance and database auto create * //This is fixed -canot be changed string UserPath = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); FILENAME = '{UserPath}\{DatabaseName}.mdf' * Work in progress - Adding more examples Co-authored-by: David Co-authored-by: raj --- src/Examples/EF6/.gitignore | 350 +++++++++ src/Examples/EF6/E1_ModelPerson/App.config | 6 + .../EF6/E1_ModelPerson/Ex1_Person.csproj | 119 +++ .../Generated_PersonModel/Person.generated.cs | 102 +++ .../PersonContext.generated.cs | 145 ++++ ...sonContextDatabaseInitializer.generated.cs | 24 + ...ntextDbMigrationConfiguration.generated.cs | 33 + .../PersonModel.generated.cs | 145 ++++ ...ersonModelDatabaseInitializer.generated.cs | 24 + ...ModelDbMigrationConfiguration.generated.cs | 33 + ... all localdb-mssqllocaldb and recreate.ps1 | 57 ++ .../EF6/E1_ModelPerson/PersonModel.cs | 1 + .../EF6/E1_ModelPerson/PersonModel.efmodel | 38 + .../PersonModel.efmodel.diagramx | 42 + .../EF6/E1_ModelPerson/PersonModel.tt | 74 ++ src/Examples/EF6/E1_ModelPerson/Program.cs | 233 ++++++ .../E1_ModelPerson/Properties/AssemblyInfo.cs | 36 + .../Properties/Resources.Designer.cs | 63 ++ .../E1_ModelPerson/Properties/Resources.resx | 117 +++ .../Properties/Settings.Designer.cs | 26 + .../Properties/Settings.settings | 7 + .../EF6/E1_ModelPerson/frmPerson.Designer.cs | 103 +++ src/Examples/EF6/E1_ModelPerson/frmPerson.cs | 102 +++ .../EF6/E1_ModelPerson/frmPerson.resx | 120 +++ .../unused/Ex3_ModelOne2Many.cs | 1 + .../unused/Ex3_ModelOne2Many.efmodel | 17 + .../unused/Ex3_ModelOne2Many.efmodel.diagramx | 17 + .../unused/Ex3_ModelOne2Many.tt | 74 ++ .../unused/Ex3_ModelOne2Many1.cs | 1 + src/Examples/EF6/EF6.sln | 55 ++ src/Examples/EF6/Ex2_ModelOne2One/App.config | 6 + .../EF6/Ex2_ModelOne2One/EFModelOne2One.cs | 1 + .../Ex2_ModelOne2One/EFModelOne2One.efmodel | 52 ++ .../EFModelOne2One.efmodel.diagramx | 40 + .../EF6/Ex2_ModelOne2One/EFModelOne2One.tt | 74 ++ .../EF6/Ex2_ModelOne2One/Ex2_ModelOne2One.cs | 1 + .../Ex2_ModelOne2One/Ex2_ModelOne2One.csproj | 111 +++ .../Ex2_ModelOne2One/Ex2_ModelOne2One.efmodel | 37 + .../Ex2_ModelOne2One.efmodel.diagramx | 34 + .../EF6/Ex2_ModelOne2One/Ex2_ModelOne2One.tt | 74 ++ .../EF6/Ex2_ModelOne2One/Ex2_ModelOne2One1.cs | 1 + .../Ex2_ModelOne2One/FrmOne2One.Designer.cs | 102 +++ .../EF6/Ex2_ModelOne2One/FrmOne2One.cs | 105 +++ .../EF6/Ex2_ModelOne2One/FrmOne2One.resx | 120 +++ .../Adress.generated.cs | 94 +++ .../ModelOne2One.generated.cs | 162 ++++ ...delOne2OneDatabaseInitializer.generated.cs | 24 + ...e2OneDbMigrationConfiguration.generated.cs | 33 + .../Person.generated.cs | 110 +++ .../Address.generated.cs | 115 +++ .../EFModelOne2One.generated.cs | 164 ++++ ...delOne2OneDatabaseInitializer.generated.cs | 24 + ...e2OneDbMigrationConfiguration.generated.cs | 33 + .../Person.generated.cs | 102 +++ src/Examples/EF6/Ex2_ModelOne2One/Program.cs | 141 ++++ .../Properties/AssemblyInfo.cs | 36 + .../Properties/Resources.Designer.cs | 70 ++ .../Properties/Resources.resx | 117 +++ .../Properties/Settings.Designer.cs | 29 + .../Properties/Settings.settings | 7 + .../EF6/Ex3_ModelManytoMany/App.config | 15 + .../Ex3_ModelManytoMany/EFModelOnetoMany.cs | 1 + .../EFModelOnetoMany.efmodel | 36 + .../EFModelOnetoMany.efmodel.diagramx | 37 + .../Ex3_ModelManytoMany/EFModelOnetoMany.tt | 74 ++ .../Ex3_ModelOnetoMany.csproj | 117 +++ .../FrmModelOnetoMany.Designer.cs | 101 +++ .../Ex3_ModelManytoMany/FrmModelOnetoMany.cs | 121 +++ .../FrmModelOnetoMany.resx | 120 +++ .../Generated_One2Many/Author.generated.cs | 76 ++ .../Generated_One2Many/Book.generated.cs | 101 +++ .../EFModelOnetoMany.generated.cs | 152 ++++ ...lOnetoManyDatabaseInitializer.generated.cs | 24 + ...oManyDbMigrationConfiguration.generated.cs | 33 + .../ModelMany2Many.efmodel | 34 + .../ModelMany2Many.efmodel.diagramx | 34 + .../EF6/Ex3_ModelManytoMany/Program.cs | 142 ++++ .../Properties/AssemblyInfo.cs | 36 + .../Properties/Resources.Designer.cs | 70 ++ .../Properties/Resources.resx | 117 +++ .../Properties/Settings.Designer.cs | 29 + .../Properties/Settings.settings | 7 + .../Ex4_ModelInvoice/AccountingSystemModel.cs | 1 + .../AccountingSystemModel.efmodel | 38 + .../AccountingSystemModel.efmodel.diagramx | 40 + .../Ex4_ModelInvoice/AccountingSystemModel.tt | 74 ++ src/Examples/EF6/Ex4_ModelInvoice/App.config | 6 + .../Ex4_ModelInvoice/Ex4_ModelInvoice.csproj | 112 +++ .../Ex4_ModelInvoice/FRmInvoice.Designer.cs | 101 +++ .../EF6/Ex4_ModelInvoice/FRmInvoice.cs | 113 +++ .../EF6/Ex4_ModelInvoice/FRmInvoice.resx | 120 +++ .../AccountingSystemModel.generated.cs | 143 ++++ ...ystemModelDatabaseInitializer.generated.cs | 24 + ...ModelDbMigrationConfiguration.generated.cs | 33 + .../InvoiceDetails.generated.cs | 105 +++ .../InvoiceHeaders.generated.cs | 64 ++ src/Examples/EF6/Ex4_ModelInvoice/Program.cs | 141 ++++ .../Properties/AssemblyInfo.cs | 36 + .../Properties/Resources.Designer.cs | 70 ++ .../Properties/Resources.resx | 117 +++ .../Properties/Settings.Designer.cs | 29 + .../Properties/Settings.settings | 7 + src/Examples/EF6/Ex5_Store/App.config | 6 + src/Examples/EF6/Ex5_Store/EFCRM.cs | 1 + src/Examples/EF6/Ex5_Store/EFCRM.efmodel | 255 ++++++ .../EF6/Ex5_Store/EFCRM.efmodel.diagramx | 178 +++++ src/Examples/EF6/Ex5_Store/EFCRM.tt | 74 ++ .../EF6/Ex5_Store/EFModelFirstDemo-master.zip | Bin 0 -> 24923 bytes .../EFModelFirstDemo-master/.gitattributes | 63 ++ .../EFModelFirstDemo-master/.gitignore | 261 +++++++ .../EFModelFirstDemo.sln | 25 + .../EFModelFirstDemo/App.config | 23 + .../EFModelFirstDemo/Course.cs | 30 + .../EFModelFirstDemo/EFModelFirstDemo.csproj | 109 +++ .../EFModelFirstDemo/Enrollement.cs | 27 + .../ModelFirstDemoDB.Context.cs | 32 + .../ModelFirstDemoDB.Context.tt | 636 +++++++++++++++ .../ModelFirstDemoDB.Designer.cs | 10 + .../EFModelFirstDemo/ModelFirstDemoDB.cs | 9 + .../EFModelFirstDemo/ModelFirstDemoDB.edmx | 205 +++++ .../ModelFirstDemoDB.edmx.diagram | 16 + .../ModelFirstDemoDB.edmx.sql | 116 +++ .../EFModelFirstDemo/ModelFirstDemoDB.tt | 733 ++++++++++++++++++ .../EFModelFirstDemo/Program.cs | 17 + .../Properties/AssemblyInfo.cs | 36 + .../EFModelFirstDemo/Student.cs | 31 + .../EFModelFirstDemo/packages.config | 4 + src/Examples/EF6/Ex5_Store/Ex6_CRM.csproj | 123 +++ .../EF6/Ex5_Store/FrmEx6CRM.Designer.cs | 63 ++ src/Examples/EF6/Ex5_Store/FrmEx6CRM.cs | 27 + src/Examples/EF6/Ex5_Store/FrmEx6CRM.resx | 120 +++ .../Ex5_Store/Generated/Address.generated.cs | 97 +++ .../Ex5_Store/Generated/Agent.generated.cs | 115 +++ .../Ex5_Store/Generated/Audit.generated.cs | 145 ++++ .../Ex5_Store/Generated/EFCRM.generated.cs | 275 +++++++ .../EFCRMDatabaseInitializer.generated.cs | 24 + ...EFCRMDbMigrationConfiguration.generated.cs | 33 + .../Ex5_Store/Generated/Features.generated.cs | 54 ++ .../EF6/Ex5_Store/Generated/Open.generated.cs | 115 +++ .../Ex5_Store/Generated/Person.generated.cs | 87 +++ .../Generated/PropertyStatus.generated.cs | 54 ++ .../Generated/PropertyType.generated.cs | 32 + .../Generated/RatingType.generated.cs | 34 + .../Generated/ResultType.generated.cs | 28 + .../Ex5_Store/Generated/Status.generated.cs | 26 + .../Ex5_Store/Generated/Tasks.generated.cs | 109 +++ .../Generated/Templates.generated.cs | 54 ++ .../Ex5_Store/Generated/Viewing.generated.cs | 117 +++ src/Examples/EF6/Ex5_Store/Program.cs | 139 ++++ .../EF6/Ex5_Store/Properties/AssemblyInfo.cs | 36 + .../Properties/Resources.Designer.cs | 70 ++ .../EF6/Ex5_Store/Properties/Resources.resx | 117 +++ .../Ex5_Store/Properties/Settings.Designer.cs | 29 + .../Ex5_Store/Properties/Settings.settings | 7 + src/Examples/EF6/Ex6_Course/App.config | 6 + src/Examples/EF6/Ex6_Course/CourseManager.cs | 1 + .../EF6/Ex6_Course/CourseManager.efmodel | 52 ++ .../Ex6_Course/CourseManager.efmodel.diagramx | 60 ++ src/Examples/EF6/Ex6_Course/CourseManager.tt | 74 ++ src/Examples/EF6/Ex6_Course/Ex5_Course.csproj | 114 +++ .../Ex6_Course/FrmCourseManager.Designer.cs | 612 +++++++++++++++ .../EF6/Ex6_Course/FrmCourseManager.cs | 682 ++++++++++++++++ .../EF6/Ex6_Course/FrmCourseManager.resx | 120 +++ .../Ex6_Course/Generated/Course.generated.cs | 71 ++ .../Generated/CourseManager.generated.cs | 156 ++++ ...rseManagerDatabaseInitializer.generated.cs | 24 + ...nagerDbMigrationConfiguration.generated.cs | 33 + .../Generated/Enrollment.generated.cs | 104 +++ .../Ex6_Course/Generated/Student.generated.cs | 64 ++ src/Examples/EF6/Ex6_Course/Program.cs | 144 ++++ .../EF6/Ex6_Course/Properties/AssemblyInfo.cs | 36 + .../Properties/Resources.Designer.cs | 63 ++ .../EF6/Ex6_Course/Properties/Resources.resx | 117 +++ .../Properties/Settings.Designer.cs | 26 + .../Ex6_Course/Properties/Settings.settings | 7 + src/Examples/EF6/README.md | 37 + 176 files changed, 14665 insertions(+) create mode 100644 src/Examples/EF6/.gitignore create mode 100644 src/Examples/EF6/E1_ModelPerson/App.config create mode 100644 src/Examples/EF6/E1_ModelPerson/Ex1_Person.csproj create mode 100644 src/Examples/EF6/E1_ModelPerson/Generated_PersonModel/Person.generated.cs create mode 100644 src/Examples/EF6/E1_ModelPerson/Generated_PersonModel/PersonContext.generated.cs create mode 100644 src/Examples/EF6/E1_ModelPerson/Generated_PersonModel/PersonContextDatabaseInitializer.generated.cs create mode 100644 src/Examples/EF6/E1_ModelPerson/Generated_PersonModel/PersonContextDbMigrationConfiguration.generated.cs create mode 100644 src/Examples/EF6/E1_ModelPerson/Generated_PersonModel/PersonModel.generated.cs create mode 100644 src/Examples/EF6/E1_ModelPerson/Generated_PersonModel/PersonModelDatabaseInitializer.generated.cs create mode 100644 src/Examples/EF6/E1_ModelPerson/Generated_PersonModel/PersonModelDbMigrationConfiguration.generated.cs create mode 100644 src/Examples/EF6/E1_ModelPerson/LocalDb-Scripts/Ps Delete all localdb-mssqllocaldb and recreate.ps1 create mode 100644 src/Examples/EF6/E1_ModelPerson/PersonModel.cs create mode 100644 src/Examples/EF6/E1_ModelPerson/PersonModel.efmodel create mode 100644 src/Examples/EF6/E1_ModelPerson/PersonModel.efmodel.diagramx create mode 100644 src/Examples/EF6/E1_ModelPerson/PersonModel.tt create mode 100644 src/Examples/EF6/E1_ModelPerson/Program.cs create mode 100644 src/Examples/EF6/E1_ModelPerson/Properties/AssemblyInfo.cs create mode 100644 src/Examples/EF6/E1_ModelPerson/Properties/Resources.Designer.cs create mode 100644 src/Examples/EF6/E1_ModelPerson/Properties/Resources.resx create mode 100644 src/Examples/EF6/E1_ModelPerson/Properties/Settings.Designer.cs create mode 100644 src/Examples/EF6/E1_ModelPerson/Properties/Settings.settings create mode 100644 src/Examples/EF6/E1_ModelPerson/frmPerson.Designer.cs create mode 100644 src/Examples/EF6/E1_ModelPerson/frmPerson.cs create mode 100644 src/Examples/EF6/E1_ModelPerson/frmPerson.resx create mode 100644 src/Examples/EF6/E1_ModelPerson/unused/Ex3_ModelOne2Many.cs create mode 100644 src/Examples/EF6/E1_ModelPerson/unused/Ex3_ModelOne2Many.efmodel create mode 100644 src/Examples/EF6/E1_ModelPerson/unused/Ex3_ModelOne2Many.efmodel.diagramx create mode 100644 src/Examples/EF6/E1_ModelPerson/unused/Ex3_ModelOne2Many.tt create mode 100644 src/Examples/EF6/E1_ModelPerson/unused/Ex3_ModelOne2Many1.cs create mode 100644 src/Examples/EF6/EF6.sln create mode 100644 src/Examples/EF6/Ex2_ModelOne2One/App.config create mode 100644 src/Examples/EF6/Ex2_ModelOne2One/EFModelOne2One.cs create mode 100644 src/Examples/EF6/Ex2_ModelOne2One/EFModelOne2One.efmodel create mode 100644 src/Examples/EF6/Ex2_ModelOne2One/EFModelOne2One.efmodel.diagramx create mode 100644 src/Examples/EF6/Ex2_ModelOne2One/EFModelOne2One.tt create mode 100644 src/Examples/EF6/Ex2_ModelOne2One/Ex2_ModelOne2One.cs create mode 100644 src/Examples/EF6/Ex2_ModelOne2One/Ex2_ModelOne2One.csproj create mode 100644 src/Examples/EF6/Ex2_ModelOne2One/Ex2_ModelOne2One.efmodel create mode 100644 src/Examples/EF6/Ex2_ModelOne2One/Ex2_ModelOne2One.efmodel.diagramx create mode 100644 src/Examples/EF6/Ex2_ModelOne2One/Ex2_ModelOne2One.tt create mode 100644 src/Examples/EF6/Ex2_ModelOne2One/Ex2_ModelOne2One1.cs create mode 100644 src/Examples/EF6/Ex2_ModelOne2One/FrmOne2One.Designer.cs create mode 100644 src/Examples/EF6/Ex2_ModelOne2One/FrmOne2One.cs create mode 100644 src/Examples/EF6/Ex2_ModelOne2One/FrmOne2One.resx create mode 100644 src/Examples/EF6/Ex2_ModelOne2One/Generated_Ex2_ModelOne2One/Adress.generated.cs create mode 100644 src/Examples/EF6/Ex2_ModelOne2One/Generated_Ex2_ModelOne2One/ModelOne2One.generated.cs create mode 100644 src/Examples/EF6/Ex2_ModelOne2One/Generated_Ex2_ModelOne2One/ModelOne2OneDatabaseInitializer.generated.cs create mode 100644 src/Examples/EF6/Ex2_ModelOne2One/Generated_Ex2_ModelOne2One/ModelOne2OneDbMigrationConfiguration.generated.cs create mode 100644 src/Examples/EF6/Ex2_ModelOne2One/Generated_Ex2_ModelOne2One/Person.generated.cs create mode 100644 src/Examples/EF6/Ex2_ModelOne2One/Generated_ModelOne2One/Address.generated.cs create mode 100644 src/Examples/EF6/Ex2_ModelOne2One/Generated_ModelOne2One/EFModelOne2One.generated.cs create mode 100644 src/Examples/EF6/Ex2_ModelOne2One/Generated_ModelOne2One/EFModelOne2OneDatabaseInitializer.generated.cs create mode 100644 src/Examples/EF6/Ex2_ModelOne2One/Generated_ModelOne2One/EFModelOne2OneDbMigrationConfiguration.generated.cs create mode 100644 src/Examples/EF6/Ex2_ModelOne2One/Generated_ModelOne2One/Person.generated.cs create mode 100644 src/Examples/EF6/Ex2_ModelOne2One/Program.cs create mode 100644 src/Examples/EF6/Ex2_ModelOne2One/Properties/AssemblyInfo.cs create mode 100644 src/Examples/EF6/Ex2_ModelOne2One/Properties/Resources.Designer.cs create mode 100644 src/Examples/EF6/Ex2_ModelOne2One/Properties/Resources.resx create mode 100644 src/Examples/EF6/Ex2_ModelOne2One/Properties/Settings.Designer.cs create mode 100644 src/Examples/EF6/Ex2_ModelOne2One/Properties/Settings.settings create mode 100644 src/Examples/EF6/Ex3_ModelManytoMany/App.config create mode 100644 src/Examples/EF6/Ex3_ModelManytoMany/EFModelOnetoMany.cs create mode 100644 src/Examples/EF6/Ex3_ModelManytoMany/EFModelOnetoMany.efmodel create mode 100644 src/Examples/EF6/Ex3_ModelManytoMany/EFModelOnetoMany.efmodel.diagramx create mode 100644 src/Examples/EF6/Ex3_ModelManytoMany/EFModelOnetoMany.tt create mode 100644 src/Examples/EF6/Ex3_ModelManytoMany/Ex3_ModelOnetoMany.csproj create mode 100644 src/Examples/EF6/Ex3_ModelManytoMany/FrmModelOnetoMany.Designer.cs create mode 100644 src/Examples/EF6/Ex3_ModelManytoMany/FrmModelOnetoMany.cs create mode 100644 src/Examples/EF6/Ex3_ModelManytoMany/FrmModelOnetoMany.resx create mode 100644 src/Examples/EF6/Ex3_ModelManytoMany/Generated_One2Many/Author.generated.cs create mode 100644 src/Examples/EF6/Ex3_ModelManytoMany/Generated_One2Many/Book.generated.cs create mode 100644 src/Examples/EF6/Ex3_ModelManytoMany/Generated_One2Many/EFModelOnetoMany.generated.cs create mode 100644 src/Examples/EF6/Ex3_ModelManytoMany/Generated_One2Many/EFModelOnetoManyDatabaseInitializer.generated.cs create mode 100644 src/Examples/EF6/Ex3_ModelManytoMany/Generated_One2Many/EFModelOnetoManyDbMigrationConfiguration.generated.cs create mode 100644 src/Examples/EF6/Ex3_ModelManytoMany/ModelMany2Many.efmodel create mode 100644 src/Examples/EF6/Ex3_ModelManytoMany/ModelMany2Many.efmodel.diagramx create mode 100644 src/Examples/EF6/Ex3_ModelManytoMany/Program.cs create mode 100644 src/Examples/EF6/Ex3_ModelManytoMany/Properties/AssemblyInfo.cs create mode 100644 src/Examples/EF6/Ex3_ModelManytoMany/Properties/Resources.Designer.cs create mode 100644 src/Examples/EF6/Ex3_ModelManytoMany/Properties/Resources.resx create mode 100644 src/Examples/EF6/Ex3_ModelManytoMany/Properties/Settings.Designer.cs create mode 100644 src/Examples/EF6/Ex3_ModelManytoMany/Properties/Settings.settings create mode 100644 src/Examples/EF6/Ex4_ModelInvoice/AccountingSystemModel.cs create mode 100644 src/Examples/EF6/Ex4_ModelInvoice/AccountingSystemModel.efmodel create mode 100644 src/Examples/EF6/Ex4_ModelInvoice/AccountingSystemModel.efmodel.diagramx create mode 100644 src/Examples/EF6/Ex4_ModelInvoice/AccountingSystemModel.tt create mode 100644 src/Examples/EF6/Ex4_ModelInvoice/App.config create mode 100644 src/Examples/EF6/Ex4_ModelInvoice/Ex4_ModelInvoice.csproj create mode 100644 src/Examples/EF6/Ex4_ModelInvoice/FRmInvoice.Designer.cs create mode 100644 src/Examples/EF6/Ex4_ModelInvoice/FRmInvoice.cs create mode 100644 src/Examples/EF6/Ex4_ModelInvoice/FRmInvoice.resx create mode 100644 src/Examples/EF6/Ex4_ModelInvoice/GeneratedAccountingModel/AccountingSystemModel.generated.cs create mode 100644 src/Examples/EF6/Ex4_ModelInvoice/GeneratedAccountingModel/AccountingSystemModelDatabaseInitializer.generated.cs create mode 100644 src/Examples/EF6/Ex4_ModelInvoice/GeneratedAccountingModel/AccountingSystemModelDbMigrationConfiguration.generated.cs create mode 100644 src/Examples/EF6/Ex4_ModelInvoice/GeneratedAccountingModel/InvoiceDetails.generated.cs create mode 100644 src/Examples/EF6/Ex4_ModelInvoice/GeneratedAccountingModel/InvoiceHeaders.generated.cs create mode 100644 src/Examples/EF6/Ex4_ModelInvoice/Program.cs create mode 100644 src/Examples/EF6/Ex4_ModelInvoice/Properties/AssemblyInfo.cs create mode 100644 src/Examples/EF6/Ex4_ModelInvoice/Properties/Resources.Designer.cs create mode 100644 src/Examples/EF6/Ex4_ModelInvoice/Properties/Resources.resx create mode 100644 src/Examples/EF6/Ex4_ModelInvoice/Properties/Settings.Designer.cs create mode 100644 src/Examples/EF6/Ex4_ModelInvoice/Properties/Settings.settings create mode 100644 src/Examples/EF6/Ex5_Store/App.config create mode 100644 src/Examples/EF6/Ex5_Store/EFCRM.cs create mode 100644 src/Examples/EF6/Ex5_Store/EFCRM.efmodel create mode 100644 src/Examples/EF6/Ex5_Store/EFCRM.efmodel.diagramx create mode 100644 src/Examples/EF6/Ex5_Store/EFCRM.tt create mode 100644 src/Examples/EF6/Ex5_Store/EFModelFirstDemo-master.zip create mode 100644 src/Examples/EF6/Ex5_Store/EFModelFirstDemo-master/.gitattributes create mode 100644 src/Examples/EF6/Ex5_Store/EFModelFirstDemo-master/.gitignore create mode 100644 src/Examples/EF6/Ex5_Store/EFModelFirstDemo-master/EFModelFirstDemo.sln create mode 100644 src/Examples/EF6/Ex5_Store/EFModelFirstDemo-master/EFModelFirstDemo/App.config create mode 100644 src/Examples/EF6/Ex5_Store/EFModelFirstDemo-master/EFModelFirstDemo/Course.cs create mode 100644 src/Examples/EF6/Ex5_Store/EFModelFirstDemo-master/EFModelFirstDemo/EFModelFirstDemo.csproj create mode 100644 src/Examples/EF6/Ex5_Store/EFModelFirstDemo-master/EFModelFirstDemo/Enrollement.cs create mode 100644 src/Examples/EF6/Ex5_Store/EFModelFirstDemo-master/EFModelFirstDemo/ModelFirstDemoDB.Context.cs create mode 100644 src/Examples/EF6/Ex5_Store/EFModelFirstDemo-master/EFModelFirstDemo/ModelFirstDemoDB.Context.tt create mode 100644 src/Examples/EF6/Ex5_Store/EFModelFirstDemo-master/EFModelFirstDemo/ModelFirstDemoDB.Designer.cs create mode 100644 src/Examples/EF6/Ex5_Store/EFModelFirstDemo-master/EFModelFirstDemo/ModelFirstDemoDB.cs create mode 100644 src/Examples/EF6/Ex5_Store/EFModelFirstDemo-master/EFModelFirstDemo/ModelFirstDemoDB.edmx create mode 100644 src/Examples/EF6/Ex5_Store/EFModelFirstDemo-master/EFModelFirstDemo/ModelFirstDemoDB.edmx.diagram create mode 100644 src/Examples/EF6/Ex5_Store/EFModelFirstDemo-master/EFModelFirstDemo/ModelFirstDemoDB.edmx.sql create mode 100644 src/Examples/EF6/Ex5_Store/EFModelFirstDemo-master/EFModelFirstDemo/ModelFirstDemoDB.tt create mode 100644 src/Examples/EF6/Ex5_Store/EFModelFirstDemo-master/EFModelFirstDemo/Program.cs create mode 100644 src/Examples/EF6/Ex5_Store/EFModelFirstDemo-master/EFModelFirstDemo/Properties/AssemblyInfo.cs create mode 100644 src/Examples/EF6/Ex5_Store/EFModelFirstDemo-master/EFModelFirstDemo/Student.cs create mode 100644 src/Examples/EF6/Ex5_Store/EFModelFirstDemo-master/EFModelFirstDemo/packages.config create mode 100644 src/Examples/EF6/Ex5_Store/Ex6_CRM.csproj create mode 100644 src/Examples/EF6/Ex5_Store/FrmEx6CRM.Designer.cs create mode 100644 src/Examples/EF6/Ex5_Store/FrmEx6CRM.cs create mode 100644 src/Examples/EF6/Ex5_Store/FrmEx6CRM.resx create mode 100644 src/Examples/EF6/Ex5_Store/Generated/Address.generated.cs create mode 100644 src/Examples/EF6/Ex5_Store/Generated/Agent.generated.cs create mode 100644 src/Examples/EF6/Ex5_Store/Generated/Audit.generated.cs create mode 100644 src/Examples/EF6/Ex5_Store/Generated/EFCRM.generated.cs create mode 100644 src/Examples/EF6/Ex5_Store/Generated/EFCRMDatabaseInitializer.generated.cs create mode 100644 src/Examples/EF6/Ex5_Store/Generated/EFCRMDbMigrationConfiguration.generated.cs create mode 100644 src/Examples/EF6/Ex5_Store/Generated/Features.generated.cs create mode 100644 src/Examples/EF6/Ex5_Store/Generated/Open.generated.cs create mode 100644 src/Examples/EF6/Ex5_Store/Generated/Person.generated.cs create mode 100644 src/Examples/EF6/Ex5_Store/Generated/PropertyStatus.generated.cs create mode 100644 src/Examples/EF6/Ex5_Store/Generated/PropertyType.generated.cs create mode 100644 src/Examples/EF6/Ex5_Store/Generated/RatingType.generated.cs create mode 100644 src/Examples/EF6/Ex5_Store/Generated/ResultType.generated.cs create mode 100644 src/Examples/EF6/Ex5_Store/Generated/Status.generated.cs create mode 100644 src/Examples/EF6/Ex5_Store/Generated/Tasks.generated.cs create mode 100644 src/Examples/EF6/Ex5_Store/Generated/Templates.generated.cs create mode 100644 src/Examples/EF6/Ex5_Store/Generated/Viewing.generated.cs create mode 100644 src/Examples/EF6/Ex5_Store/Program.cs create mode 100644 src/Examples/EF6/Ex5_Store/Properties/AssemblyInfo.cs create mode 100644 src/Examples/EF6/Ex5_Store/Properties/Resources.Designer.cs create mode 100644 src/Examples/EF6/Ex5_Store/Properties/Resources.resx create mode 100644 src/Examples/EF6/Ex5_Store/Properties/Settings.Designer.cs create mode 100644 src/Examples/EF6/Ex5_Store/Properties/Settings.settings create mode 100644 src/Examples/EF6/Ex6_Course/App.config create mode 100644 src/Examples/EF6/Ex6_Course/CourseManager.cs create mode 100644 src/Examples/EF6/Ex6_Course/CourseManager.efmodel create mode 100644 src/Examples/EF6/Ex6_Course/CourseManager.efmodel.diagramx create mode 100644 src/Examples/EF6/Ex6_Course/CourseManager.tt create mode 100644 src/Examples/EF6/Ex6_Course/Ex5_Course.csproj create mode 100644 src/Examples/EF6/Ex6_Course/FrmCourseManager.Designer.cs create mode 100644 src/Examples/EF6/Ex6_Course/FrmCourseManager.cs create mode 100644 src/Examples/EF6/Ex6_Course/FrmCourseManager.resx create mode 100644 src/Examples/EF6/Ex6_Course/Generated/Course.generated.cs create mode 100644 src/Examples/EF6/Ex6_Course/Generated/CourseManager.generated.cs create mode 100644 src/Examples/EF6/Ex6_Course/Generated/CourseManagerDatabaseInitializer.generated.cs create mode 100644 src/Examples/EF6/Ex6_Course/Generated/CourseManagerDbMigrationConfiguration.generated.cs create mode 100644 src/Examples/EF6/Ex6_Course/Generated/Enrollment.generated.cs create mode 100644 src/Examples/EF6/Ex6_Course/Generated/Student.generated.cs create mode 100644 src/Examples/EF6/Ex6_Course/Program.cs create mode 100644 src/Examples/EF6/Ex6_Course/Properties/AssemblyInfo.cs create mode 100644 src/Examples/EF6/Ex6_Course/Properties/Resources.Designer.cs create mode 100644 src/Examples/EF6/Ex6_Course/Properties/Resources.resx create mode 100644 src/Examples/EF6/Ex6_Course/Properties/Settings.Designer.cs create mode 100644 src/Examples/EF6/Ex6_Course/Properties/Settings.settings create mode 100644 src/Examples/EF6/README.md diff --git a/src/Examples/EF6/.gitignore b/src/Examples/EF6/.gitignore new file mode 100644 index 000000000..dfcfd56f4 --- /dev/null +++ b/src/Examples/EF6/.gitignore @@ -0,0 +1,350 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ +[Ll]ogs/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ diff --git a/src/Examples/EF6/E1_ModelPerson/App.config b/src/Examples/EF6/E1_ModelPerson/App.config new file mode 100644 index 000000000..193aecc67 --- /dev/null +++ b/src/Examples/EF6/E1_ModelPerson/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/src/Examples/EF6/E1_ModelPerson/Ex1_Person.csproj b/src/Examples/EF6/E1_ModelPerson/Ex1_Person.csproj new file mode 100644 index 000000000..f8036dd2c --- /dev/null +++ b/src/Examples/EF6/E1_ModelPerson/Ex1_Person.csproj @@ -0,0 +1,119 @@ + + + + + Debug + AnyCPU + {B0C345BB-4B38-44CE-8D42-3E00545347BA} + WinExe + Ex1_Person + Ex1_Person + v4.8 + 512 + true + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + Ex1_Person.Program + + + + + + + + + + + + + + + + + + + Form + + + frmPerson.cs + + + + + + + True + True + PersonModel.tt + + + + + frmPerson.cs + + + ResXFileCodeGenerator + Resources.Designer.cs + Designer + + + True + Resources.resx + True + + + + PersonModel.efmodel + + + SettingsSingleFileGenerator + Settings.Designer.cs + + + True + Settings.settings + True + + + + + + + + 6.4.4 + + + + + + + + + + + TextTemplatingFileGenerator + PersonModel.cs + + + + \ No newline at end of file diff --git a/src/Examples/EF6/E1_ModelPerson/Generated_PersonModel/Person.generated.cs b/src/Examples/EF6/E1_ModelPerson/Generated_PersonModel/Person.generated.cs new file mode 100644 index 000000000..93fd8673b --- /dev/null +++ b/src/Examples/EF6/E1_ModelPerson/Generated_PersonModel/Person.generated.cs @@ -0,0 +1,102 @@ +//------------------------------------------------------------------------------ +// +// This code was generated from a template. +// +// Manual changes to this file may cause unexpected behavior in your application. +// Manual changes to this file will be overwritten if the code is regenerated. +// +// Produced by Entity Framework Visual Editor v3.0.7.2 +// Source: https://github.com/msawczyn/EFDesigner +// Visual Studio Marketplace: https://marketplace.visualstudio.com/items?itemName=michaelsawczyn.EFDesigner +// Documentation: https://msawczyn.github.io/EFDesigner/ +// License (MIT): https://github.com/msawczyn/EFDesigner/blob/master/LICENSE +// +//------------------------------------------------------------------------------ + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using System.Linq; +using System.Runtime.CompilerServices; + +namespace Ex1_Person +{ + public partial class Person + { + partial void Init(); + + /// + /// Default constructor + /// + public Person() + { + Init(); + } + + /************************************************************************* + * Properties + *************************************************************************/ + + /// + /// Identity, Required + /// + [Key] + [Required] + public long Id { get; set; } + + /// + /// Max length = 25 + /// + [MaxLength(25)] + [StringLength(25)] + public string FirstName { get; set; } + + /// + /// Max length = 35 + /// + [MaxLength(35)] + [StringLength(35)] + public string MiddleName { get; set; } + + /// + /// Max length = 35 + /// + [MaxLength(35)] + [StringLength(35)] + public string LastName { get; set; } + + /// + /// Max length = 75 + /// + [MaxLength(75)] + [StringLength(75)] + public string PreferredName { get; set; } + + public DateTime? DOB { get; set; } + + /// + /// Max length = 45 + /// + [MaxLength(45)] + [StringLength(45)] + public string Email { get; set; } + + /// + /// Max length = 15 + /// + [MaxLength(15)] + [StringLength(15)] + public string Phone { get; set; } + + /// + /// Concurrency token + /// + [Timestamp] + public Byte[] Timestamp { get; set; } + + } +} + diff --git a/src/Examples/EF6/E1_ModelPerson/Generated_PersonModel/PersonContext.generated.cs b/src/Examples/EF6/E1_ModelPerson/Generated_PersonModel/PersonContext.generated.cs new file mode 100644 index 000000000..6ce6f437c --- /dev/null +++ b/src/Examples/EF6/E1_ModelPerson/Generated_PersonModel/PersonContext.generated.cs @@ -0,0 +1,145 @@ +//------------------------------------------------------------------------------ +// +// This code was generated from a template. +// +// Manual changes to this file may cause unexpected behavior in your application. +// Manual changes to this file will be overwritten if the code is regenerated. +// +// Produced by Entity Framework Visual Editor v3.0.7.2 +// Source: https://github.com/msawczyn/EFDesigner +// Visual Studio Marketplace: https://marketplace.visualstudio.com/items?itemName=michaelsawczyn.EFDesigner +// Documentation: https://msawczyn.github.io/EFDesigner/ +// License (MIT): https://github.com/msawczyn/EFDesigner/blob/master/LICENSE +// +//------------------------------------------------------------------------------ + +using System; +using System.Collections.Generic; +using System.Linq; +using System.ComponentModel.DataAnnotations.Schema; +using System.Data.Entity; +using System.Data.Entity.Infrastructure.Annotations; + +namespace Ex1_Person +{ + /// + public partial class PersonContext : DbContext + { + #region DbSets + public virtual System.Data.Entity.DbSet People { get; set; } + #endregion DbSets + + #region Constructors + + partial void CustomInit(); + + /// + /// Default connection string + /// + public static string ConnectionString { get; set; } = @"Data Source=(localdb)\dbinstance;Initial Catalog=EFLocalDb;Integrated Security=True"; + /// + public PersonContext() : base(ConnectionString) + { + Configuration.LazyLoadingEnabled = true; + Configuration.ProxyCreationEnabled = true; + System.Data.Entity.Database.SetInitializer(new PersonContextDatabaseInitializer()); + CustomInit(); + } + + /// + public PersonContext(string connectionString) : base(connectionString) + { + Configuration.LazyLoadingEnabled = true; + Configuration.ProxyCreationEnabled = true; + System.Data.Entity.Database.SetInitializer(new PersonContextDatabaseInitializer()); + CustomInit(); + } + + /// + public PersonContext(string connectionString, System.Data.Entity.Infrastructure.DbCompiledModel model) : base(connectionString, model) + { + Configuration.LazyLoadingEnabled = true; + Configuration.ProxyCreationEnabled = true; + System.Data.Entity.Database.SetInitializer(new PersonContextDatabaseInitializer()); + CustomInit(); + } + + /// + public PersonContext(System.Data.Common.DbConnection existingConnection, bool contextOwnsConnection) : base(existingConnection, contextOwnsConnection) + { + Configuration.LazyLoadingEnabled = true; + Configuration.ProxyCreationEnabled = true; + System.Data.Entity.Database.SetInitializer(new PersonContextDatabaseInitializer()); + CustomInit(); + } + + /// + public PersonContext(System.Data.Common.DbConnection existingConnection, System.Data.Entity.Infrastructure.DbCompiledModel model, bool contextOwnsConnection) : base(existingConnection, model, contextOwnsConnection) + { + Configuration.LazyLoadingEnabled = true; + Configuration.ProxyCreationEnabled = true; + System.Data.Entity.Database.SetInitializer(new PersonContextDatabaseInitializer()); + CustomInit(); + } + + /// + public PersonContext(System.Data.Entity.Infrastructure.DbCompiledModel model) : base(model) + { + Configuration.LazyLoadingEnabled = true; + Configuration.ProxyCreationEnabled = true; + System.Data.Entity.Database.SetInitializer(new PersonContextDatabaseInitializer()); + CustomInit(); + } + + /// + public PersonContext(System.Data.Entity.Core.Objects.ObjectContext objectContext, bool dbContextOwnsObjectContext) : base(objectContext, dbContextOwnsObjectContext) + { + Configuration.LazyLoadingEnabled = true; + Configuration.ProxyCreationEnabled = true; + System.Data.Entity.Database.SetInitializer(new PersonContextDatabaseInitializer()); + CustomInit(); + } + + #endregion Constructors + + partial void OnModelCreatingImpl(System.Data.Entity.DbModelBuilder modelBuilder); + partial void OnModelCreatedImpl(System.Data.Entity.DbModelBuilder modelBuilder); + + /// + protected override void OnModelCreating(System.Data.Entity.DbModelBuilder modelBuilder) + { + base.OnModelCreating(modelBuilder); + OnModelCreatingImpl(modelBuilder); + + modelBuilder.HasDefaultSchema("dbo"); + + modelBuilder.Entity() + .ToTable("People") + .HasKey(t => t.Id); + modelBuilder.Entity() + .Property(t => t.Id) + .IsRequired() + .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity); + modelBuilder.Entity() + .Property(t => t.FirstName) + .HasMaxLength(25); + modelBuilder.Entity() + .Property(t => t.MiddleName) + .HasMaxLength(35); + modelBuilder.Entity() + .Property(t => t.LastName) + .HasMaxLength(35); + modelBuilder.Entity() + .Property(t => t.PreferredName) + .HasMaxLength(75); + modelBuilder.Entity() + .Property(t => t.Email) + .HasMaxLength(45); + modelBuilder.Entity() + .Property(t => t.Phone) + .HasMaxLength(15); + + OnModelCreatedImpl(modelBuilder); + } + } +} diff --git a/src/Examples/EF6/E1_ModelPerson/Generated_PersonModel/PersonContextDatabaseInitializer.generated.cs b/src/Examples/EF6/E1_ModelPerson/Generated_PersonModel/PersonContextDatabaseInitializer.generated.cs new file mode 100644 index 000000000..b9ad42a39 --- /dev/null +++ b/src/Examples/EF6/E1_ModelPerson/Generated_PersonModel/PersonContextDatabaseInitializer.generated.cs @@ -0,0 +1,24 @@ +//------------------------------------------------------------------------------ +// +// This code was generated from a template. +// +// Manual changes to this file may cause unexpected behavior in your application. +// Manual changes to this file will be overwritten if the code is regenerated. +// +// Produced by Entity Framework Visual Editor v3.0.7.2 +// Source: https://github.com/msawczyn/EFDesigner +// Visual Studio Marketplace: https://marketplace.visualstudio.com/items?itemName=michaelsawczyn.EFDesigner +// Documentation: https://msawczyn.github.io/EFDesigner/ +// License (MIT): https://github.com/msawczyn/EFDesigner/blob/master/LICENSE +// +//------------------------------------------------------------------------------ + +using System.Data.Entity; + +namespace Ex1_Person +{ + /// + public partial class PersonContextDatabaseInitializer : CreateDatabaseIfNotExists + { + } +} diff --git a/src/Examples/EF6/E1_ModelPerson/Generated_PersonModel/PersonContextDbMigrationConfiguration.generated.cs b/src/Examples/EF6/E1_ModelPerson/Generated_PersonModel/PersonContextDbMigrationConfiguration.generated.cs new file mode 100644 index 000000000..c88c915c5 --- /dev/null +++ b/src/Examples/EF6/E1_ModelPerson/Generated_PersonModel/PersonContextDbMigrationConfiguration.generated.cs @@ -0,0 +1,33 @@ +//------------------------------------------------------------------------------ +// +// This code was generated from a template. +// +// Manual changes to this file may cause unexpected behavior in your application. +// Manual changes to this file will be overwritten if the code is regenerated. +// +// Produced by Entity Framework Visual Editor v3.0.7.2 +// Source: https://github.com/msawczyn/EFDesigner +// Visual Studio Marketplace: https://marketplace.visualstudio.com/items?itemName=michaelsawczyn.EFDesigner +// Documentation: https://msawczyn.github.io/EFDesigner/ +// License (MIT): https://github.com/msawczyn/EFDesigner/blob/master/LICENSE +// +//------------------------------------------------------------------------------ + +using System.Data.Entity.Migrations; + +namespace Migrations +{ + /// + public sealed partial class PersonContextDbMigrationConfiguration : DbMigrationsConfiguration + { + partial void Init(); + + /// + public PersonContextDbMigrationConfiguration() + { + AutomaticMigrationsEnabled = true; + AutomaticMigrationDataLossAllowed = false; + Init(); + } + } +} diff --git a/src/Examples/EF6/E1_ModelPerson/Generated_PersonModel/PersonModel.generated.cs b/src/Examples/EF6/E1_ModelPerson/Generated_PersonModel/PersonModel.generated.cs new file mode 100644 index 000000000..0e3aaa5c3 --- /dev/null +++ b/src/Examples/EF6/E1_ModelPerson/Generated_PersonModel/PersonModel.generated.cs @@ -0,0 +1,145 @@ +//------------------------------------------------------------------------------ +// +// This code was generated from a template. +// +// Manual changes to this file may cause unexpected behavior in your application. +// Manual changes to this file will be overwritten if the code is regenerated. +// +// Produced by Entity Framework Visual Editor v3.0.7.2 +// Source: https://github.com/msawczyn/EFDesigner +// Visual Studio Marketplace: https://marketplace.visualstudio.com/items?itemName=michaelsawczyn.EFDesigner +// Documentation: https://msawczyn.github.io/EFDesigner/ +// License (MIT): https://github.com/msawczyn/EFDesigner/blob/master/LICENSE +// +//------------------------------------------------------------------------------ + +using System; +using System.Collections.Generic; +using System.Linq; +using System.ComponentModel.DataAnnotations.Schema; +using System.Data.Entity; +using System.Data.Entity.Infrastructure.Annotations; + +namespace Ex1_Person +{ + /// + public partial class PersonModel : DbContext + { + #region DbSets + public virtual System.Data.Entity.DbSet People { get; set; } + #endregion DbSets + + #region Constructors + + partial void CustomInit(); + + /// + /// Default connection string + /// + public static string ConnectionString { get; set; } = @"Data Source=(localdb)\mssqllocaldb;Initial Catalog=EFVisualExamples;Integrated Security=True"; + /// + public PersonModel() : base(ConnectionString) + { + Configuration.LazyLoadingEnabled = true; + Configuration.ProxyCreationEnabled = true; + System.Data.Entity.Database.SetInitializer(new PersonModelDatabaseInitializer()); + CustomInit(); + } + + /// + public PersonModel(string connectionString) : base(connectionString) + { + Configuration.LazyLoadingEnabled = true; + Configuration.ProxyCreationEnabled = true; + System.Data.Entity.Database.SetInitializer(new PersonModelDatabaseInitializer()); + CustomInit(); + } + + /// + public PersonModel(string connectionString, System.Data.Entity.Infrastructure.DbCompiledModel model) : base(connectionString, model) + { + Configuration.LazyLoadingEnabled = true; + Configuration.ProxyCreationEnabled = true; + System.Data.Entity.Database.SetInitializer(new PersonModelDatabaseInitializer()); + CustomInit(); + } + + /// + public PersonModel(System.Data.Common.DbConnection existingConnection, bool contextOwnsConnection) : base(existingConnection, contextOwnsConnection) + { + Configuration.LazyLoadingEnabled = true; + Configuration.ProxyCreationEnabled = true; + System.Data.Entity.Database.SetInitializer(new PersonModelDatabaseInitializer()); + CustomInit(); + } + + /// + public PersonModel(System.Data.Common.DbConnection existingConnection, System.Data.Entity.Infrastructure.DbCompiledModel model, bool contextOwnsConnection) : base(existingConnection, model, contextOwnsConnection) + { + Configuration.LazyLoadingEnabled = true; + Configuration.ProxyCreationEnabled = true; + System.Data.Entity.Database.SetInitializer(new PersonModelDatabaseInitializer()); + CustomInit(); + } + + /// + public PersonModel(System.Data.Entity.Infrastructure.DbCompiledModel model) : base(model) + { + Configuration.LazyLoadingEnabled = true; + Configuration.ProxyCreationEnabled = true; + System.Data.Entity.Database.SetInitializer(new PersonModelDatabaseInitializer()); + CustomInit(); + } + + /// + public PersonModel(System.Data.Entity.Core.Objects.ObjectContext objectContext, bool dbContextOwnsObjectContext) : base(objectContext, dbContextOwnsObjectContext) + { + Configuration.LazyLoadingEnabled = true; + Configuration.ProxyCreationEnabled = true; + System.Data.Entity.Database.SetInitializer(new PersonModelDatabaseInitializer()); + CustomInit(); + } + + #endregion Constructors + + partial void OnModelCreatingImpl(System.Data.Entity.DbModelBuilder modelBuilder); + partial void OnModelCreatedImpl(System.Data.Entity.DbModelBuilder modelBuilder); + + /// + protected override void OnModelCreating(System.Data.Entity.DbModelBuilder modelBuilder) + { + base.OnModelCreating(modelBuilder); + OnModelCreatingImpl(modelBuilder); + + modelBuilder.HasDefaultSchema("dbo"); + + modelBuilder.Entity() + .ToTable("People") + .HasKey(t => t.Id); + modelBuilder.Entity() + .Property(t => t.Id) + .IsRequired() + .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity); + modelBuilder.Entity() + .Property(t => t.FirstName) + .HasMaxLength(25); + modelBuilder.Entity() + .Property(t => t.MiddleName) + .HasMaxLength(35); + modelBuilder.Entity() + .Property(t => t.LastName) + .HasMaxLength(35); + modelBuilder.Entity() + .Property(t => t.PreferredName) + .HasMaxLength(75); + modelBuilder.Entity() + .Property(t => t.Email) + .HasMaxLength(45); + modelBuilder.Entity() + .Property(t => t.Phone) + .HasMaxLength(15); + + OnModelCreatedImpl(modelBuilder); + } + } +} diff --git a/src/Examples/EF6/E1_ModelPerson/Generated_PersonModel/PersonModelDatabaseInitializer.generated.cs b/src/Examples/EF6/E1_ModelPerson/Generated_PersonModel/PersonModelDatabaseInitializer.generated.cs new file mode 100644 index 000000000..e851e000e --- /dev/null +++ b/src/Examples/EF6/E1_ModelPerson/Generated_PersonModel/PersonModelDatabaseInitializer.generated.cs @@ -0,0 +1,24 @@ +//------------------------------------------------------------------------------ +// +// This code was generated from a template. +// +// Manual changes to this file may cause unexpected behavior in your application. +// Manual changes to this file will be overwritten if the code is regenerated. +// +// Produced by Entity Framework Visual Editor v3.0.7.2 +// Source: https://github.com/msawczyn/EFDesigner +// Visual Studio Marketplace: https://marketplace.visualstudio.com/items?itemName=michaelsawczyn.EFDesigner +// Documentation: https://msawczyn.github.io/EFDesigner/ +// License (MIT): https://github.com/msawczyn/EFDesigner/blob/master/LICENSE +// +//------------------------------------------------------------------------------ + +using System.Data.Entity; + +namespace Ex1_Person +{ + /// + public partial class PersonModelDatabaseInitializer : CreateDatabaseIfNotExists + { + } +} diff --git a/src/Examples/EF6/E1_ModelPerson/Generated_PersonModel/PersonModelDbMigrationConfiguration.generated.cs b/src/Examples/EF6/E1_ModelPerson/Generated_PersonModel/PersonModelDbMigrationConfiguration.generated.cs new file mode 100644 index 000000000..8d2222831 --- /dev/null +++ b/src/Examples/EF6/E1_ModelPerson/Generated_PersonModel/PersonModelDbMigrationConfiguration.generated.cs @@ -0,0 +1,33 @@ +//------------------------------------------------------------------------------ +// +// This code was generated from a template. +// +// Manual changes to this file may cause unexpected behavior in your application. +// Manual changes to this file will be overwritten if the code is regenerated. +// +// Produced by Entity Framework Visual Editor v3.0.7.2 +// Source: https://github.com/msawczyn/EFDesigner +// Visual Studio Marketplace: https://marketplace.visualstudio.com/items?itemName=michaelsawczyn.EFDesigner +// Documentation: https://msawczyn.github.io/EFDesigner/ +// License (MIT): https://github.com/msawczyn/EFDesigner/blob/master/LICENSE +// +//------------------------------------------------------------------------------ + +using System.Data.Entity.Migrations; + +namespace Migrations +{ + /// + public sealed partial class PersonModelDbMigrationConfiguration : DbMigrationsConfiguration + { + partial void Init(); + + /// + public PersonModelDbMigrationConfiguration() + { + AutomaticMigrationsEnabled = true; + AutomaticMigrationDataLossAllowed = false; + Init(); + } + } +} diff --git a/src/Examples/EF6/E1_ModelPerson/LocalDb-Scripts/Ps Delete all localdb-mssqllocaldb and recreate.ps1 b/src/Examples/EF6/E1_ModelPerson/LocalDb-Scripts/Ps Delete all localdb-mssqllocaldb and recreate.ps1 new file mode 100644 index 000000000..73cac17c8 --- /dev/null +++ b/src/Examples/EF6/E1_ModelPerson/LocalDb-Scripts/Ps Delete all localdb-mssqllocaldb and recreate.ps1 @@ -0,0 +1,57 @@ +Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy Unrestricted -Force; + +write-host "--WORK IN PROGRESS - Attempt to Drop and Recreate Database" + + +$DatabaseName ="EFVisualExamples" +$localUser = [System.Environment]::GetFolderPath([System.Environment+SpecialFolder]::UserProfile) + +write-host "Stopping Server Instance, so connections drop..." +sqllocaldb stop mssqllocaldb + +$oReturn=[System.Windows.Forms.MessageBox]::Show("Delete Server Instance: mssqllocaldb","Delete mssqllocaldb?",[System.Windows.Forms.MessageBoxButtons]::OKCancel) +switch ($oReturn){ + "OK" { + write-host "Deleting Server Instance..." + sqllocaldb d mssqllocaldb + } + "Cancel" { + write-host "Server Instance retained" + } +} + + + + +$mdfFile = ($localUser + "\\" + ($DatabaseName.mdf) ) +$mdfName = ($DatabaseName + "_dat") +Remove-Item -path $mdfFile + +$extnldf = "_log.ldf" +$ldfName = ($DatabaseName + "_log") +$ldfFile = ($localUser+ "\" + ($DatabaseName + $extnldf)) +Remove-Item -path ldfFile + + +$myserver = "(localdb)\MSSQLLocalDB" + +write-host "Starting Server Instance..." + +Sqlcmd -S $myserver -Q "Select @@servername" + +write-host "Creating new Database on Server Instance..." + +Sqlcmd -S $myserver -Q "USE master; + GO + CREATE DATABASE $DatabaseName + ON + ( NAME = $mdfName, + FILENAME = '$mdfFile', + SIZE = 10, + FILEGROWTH = 5 ) + LOG ON + ( NAME = $ldfName, + FILENAME = '$ldfFile', + SIZE = 5MB, + FILEGROWTH = 5MB ); + GO " \ No newline at end of file diff --git a/src/Examples/EF6/E1_ModelPerson/PersonModel.cs b/src/Examples/EF6/E1_ModelPerson/PersonModel.cs new file mode 100644 index 000000000..6153a7d78 --- /dev/null +++ b/src/Examples/EF6/E1_ModelPerson/PersonModel.cs @@ -0,0 +1 @@ + diff --git a/src/Examples/EF6/E1_ModelPerson/PersonModel.efmodel b/src/Examples/EF6/E1_ModelPerson/PersonModel.efmodel new file mode 100644 index 000000000..7577a7342 --- /dev/null +++ b/src/Examples/EF6/E1_ModelPerson/PersonModel.efmodel @@ -0,0 +1,38 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/Examples/EF6/E1_ModelPerson/PersonModel.efmodel.diagramx b/src/Examples/EF6/E1_ModelPerson/PersonModel.efmodel.diagramx new file mode 100644 index 000000000..45ba3a9f0 --- /dev/null +++ b/src/Examples/EF6/E1_ModelPerson/PersonModel.efmodel.diagramx @@ -0,0 +1,42 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/Examples/EF6/E1_ModelPerson/PersonModel.tt b/src/Examples/EF6/E1_ModelPerson/PersonModel.tt new file mode 100644 index 000000000..97b1275ec --- /dev/null +++ b/src/Examples/EF6/E1_ModelPerson/PersonModel.tt @@ -0,0 +1,74 @@ +<#@ template inherits="Microsoft.VisualStudio.TextTemplating.VSHost.ModelingTextTransformation" debug="true" + hostSpecific="true" language="C#" compilerOptions="/langversion:latest"#> +<#@ CleanupBehavior processor="T4VSHost" CleanupAfterProcessingtemplate="true" #> +<#@ assembly name="System.Data.Entity.Design.dll" +#><#@ assembly name="EnvDTE" +#><#@ include file="EFDesigner.ttinclude" once="true" +#><#@ output extension=".cs" +#><#@ import namespace="System.Linq" +#><#@ import namespace="System" +#><#@ import namespace="System.Data.Entity.Design.PluralizationServices" +#><#@ import namespace="System.Globalization" +#><#@ import namespace="Sawczyn.EFDesigner.EFModel" +#><#@ EFModel processor="EFModelDirectiveProcessor" requires="FileName='PersonModel.efmodel'" +#><# + Manager manager = Manager.Create(Host, GenerationEnvironment); + manager.FileNameMarker = ModelRoot.FileNameMarker; + + if (ModelRoot.Classes.Any()) + { + manager.StartHeader(false); + Output("//------------------------------------------------------------------------------"); + Output("// "); + Output("// This code was generated from a template."); + Output("//"); + Output("// Manual changes to this file may cause unexpected behavior in your application."); + Output("// Manual changes to this file will be overwritten if the code is regenerated."); + Output("//"); + Output("// Produced by Entity Framework Visual Editor v" + ModelRoot.DSLVersion); + Output("// Source: https://github.com/msawczyn/EFDesigner"); + Output("// Visual Studio Marketplace: https://marketplace.visualstudio.com/items?itemName=michaelsawczyn.EFDesigner"); + Output("// Documentation: https://msawczyn.github.io/EFDesigner/"); + Output("// License (MIT): https://github.com/msawczyn/EFDesigner/blob/master/LICENSE"); + Output("// "); + Output("//------------------------------------------------------------------------------"); + NL(); + + EFModelGenerator generator; + + switch (ModelRoot.EntityFrameworkVersion) + { + case EFVersion.EF6: + { + generator = new EF6ModelGenerator(this); + break; + } + + case EFVersion.EFCore: + { + switch ((int)ModelRoot.GetEntityFrameworkPackageVersionNum()) + { + case 2: + generator = new EFCore2ModelGenerator(this); + break; + + case 3: + generator = new EFCore3ModelGenerator(this); + break; + + default: + generator = new EFCore5ModelGenerator(this); + break; + } + break; + } + + default: + throw new InvalidOperationException("Unsupported Entity Framework version"); + } + + generator.Generate(manager); + } + + manager.Process(true); +#> \ No newline at end of file diff --git a/src/Examples/EF6/E1_ModelPerson/Program.cs b/src/Examples/EF6/E1_ModelPerson/Program.cs new file mode 100644 index 000000000..c663c0a12 --- /dev/null +++ b/src/Examples/EF6/E1_ModelPerson/Program.cs @@ -0,0 +1,233 @@ +using System; +using System.Collections.Generic; +using System.Data.SqlClient; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace Ex1_Person +{ + + + + // ---- Objective: Easy GUI Database create and use --- + // Uses models / classes to setup data that is then stored in a Database. + + // --------- BACKGROUND -------------- + // The no ORM (Object Relationship Model) of doing Basic Database Operations is using C# hand crafted SQL CRUD + // Works for simple database work but does not scale and is hard to maintiain. + //https://www.geeksforgeeks.org/basic-database-operations-using-c-sharp/ + + + // --------- Introducing ENTITY FRAMEWORK -------------- + // This is a modern ORM way of using DB access, robust and solid using Code First & Fluent API ( + // Unfortunatley the 'Code first' and 'Fluent API' are console like commands that require a deep dive to utilise and apply to your requirements. + + // --------- Problem -------------- + // The Entity framework Microsoft ADO.Net modeller GUI wrapper for 'Code first' and 'Fluent API' modelling tool .edmx is fragile and incomplete. + + // Microsofts .EDMX visual tools DO NOT WORK - EDMX Entitfy framework gui tools from Microsoft suck! + // DO NOT USE ->https://docs.microsoft.com/en-us/visualstudio/data-tools/entity-data-model-tools-in-visual-studio?view=vs-2019 + + + // ----------- Solution: Entity Framework Visual Editor ------------------ + // An open source EF GUI tool works, here are some examples of how you get setup to use it.. + + // It makes it easy to visualise, create and maintain complex relational databases + + + // --------- HOW TO GET SETUP -------------- + // Entity Framework Visual Editor - creates .efmodel etc from a GUI tool + //https://marketplace.visualstudio.com/items?itemName=michaelsawczyn.EFDesigner + + + // ---------- SETUP DATABASE SERVER - MsSqlServer LocalDb -------- // + + // LocalDB is a special, low impact version of the SQL Server engine, that is not installed as a Windows Service, + // but launched(made to run) on demand by the ADO.NET client opening a connection to it.It is intended for single user scenarios, and not for any production use - + // for production you should use SQL Server Express(or higher) + + //Download SQL Server Express - LocalDB + // https://www.sqlshack.com/install-microsoft-sql-server-express-localdb/ + // https://www.microsoft.com/en-au/download/confirmation.aspx?id=101064 + // Microsoft SQL Server Express LocalDB supports silent installation. A user should download SqlLocalDB.msi and run the Command Prompt window as an administrator. Then, they should paste the following command: + // msiexec /i SqlLocalDB.msi /qn IACCEPTSQLLOCALDBLICENSETERMS = YES + + + // Initialise Database File using Cmd Prompt + + /* https://www.sqlshack.com/how-to-connect-and-use-microsoft-sql-server-express-localdb/ + + C:\>sqllocaldb create DbInstance + + //Connection string is now + //Data Source=(localdb)\DbInstance;Initial Catalog=EFLocalDb;Integrated Security=True + + C:\>sqllocaldb info DbInstance + Name: DbInstance + Version: 13.1.4001.0 + Shared name: + Owner: DEV\David + Auto-create: No + State: Stopped + Last start time: 2/11/2021 1:02:19 PM + Instance pipe name: <- Pipe name entry missing, SqlLocalDB not started? Should auto start + + C:\>SqlLocalDB start v11 + LocalDB instance "v11" started. + + C:\>sqllocaldb info DbInstance + Name: DbInstance + Version: 13.1.4001.0 + Shared name: + Owner: DEV\David + Auto-create: No + State: Running + Last start time: 2/11/2021 1:04:51 PM + Instance pipe name: np:\\.\pipe\LOCALDB#385051FC\tsql\query + + */ + + // Download and Use: SSMS - Sql Server Management Studio - Create Database 'EFLocalDb' + // https://www.microsoft.com/en-au/download/details.aspx?id=101064 + // Paste your connection as (localdb)\DbInstance and use windows permisions + + // Note: SSMS database tool can hold a lock on the Database so the code cannot delete or update the database, simply close SSMS. + + //NOTE: Microsofts .EDMX visual tools DO NOT WORK - EDMX Entitfy framework gui tools from Microsoft suck! + // DO NOT USE ->https://docs.microsoft.com/en-us/visualstudio/data-tools/entity-data-model-tools-in-visual-studio?view=vs-2019 + + static class Program + { + /// + /// The main entry point for the application. + /// + [STAThread] + static void Main() + { + Application.EnableVisualStyles(); + Application.SetCompatibleTextRenderingDefault(false); + + //Match Connection string in .efmodel + //Data Source=(localdb)\mssqllocaldb;Initial Catalog=EFVisualExamples;Integrated Security=True + SetupLocalDb("mssqllocaldb", "EFVisualExamples"); + + Application.Run(new frmPerson()); + + } + + + static void SetupLocalDb(string InstanceName = "mssqllocaldb", string DatabaseName = "EFVisualExamples") //This is a default instance name in local DB v13 + { + //Step 1: Islocaldb installed? + if (!CreateLocalDBInstance(InstanceName)) + { + + MessageBox.Show("CRITICAL ERROR: SqlLocalDb software is not installed!"); + + //Download SQL Server Express - LocalDB + // https://www.sqlshack.com/install-microsoft-sql-server-express-localdb/ + // https://www.microsoft.com/en-au/download/confirmation.aspx?id=101064 + // Microsoft SQL Server Express LocalDB supports silent installation. A user should download SqlLocalDB.msi and run the Command Prompt window as an administrator. Then, they should paste the following command: + // msiexec /i SqlLocalDB.msi /qn IACCEPTSQLLOCALDBLICENSETERMS = YES + string url = @"https://www.microsoft.com/en-au/download/confirmation.aspx?id=101064"; + Process.Start(url); + + Application.Exit(); + } + + //Step2: Create Database + + string connectionString = @"Data Source=(localdb)\" + InstanceName + $"; Integrated Security=True;"; + + if (!CheckDatabaseExists(connectionString, DatabaseName)) + { + //This is fixed -canot be changed + string UserPath = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); + + + SqlConnection connection = new SqlConnection(connectionString); + using (connection) + { + connection.Open(); + + string sql = $@" + CREATE DATABASE + {DatabaseName} + ON PRIMARY ( + NAME={DatabaseName}_data, + FILENAME = '{UserPath}\{DatabaseName}.mdf' + ) + LOG ON ( + NAME={DatabaseName}_log, + FILENAME = '{UserPath}\{DatabaseName}.ldf' + )"; + + SqlCommand command = new SqlCommand(sql, connection); + try + { + command.ExecuteNonQuery(); + } + catch (Exception ex) + { + MessageBox.Show($"CRITICAL ERROR: Database cannot be created\r\n{ex.ToString()}\r\nDoes Db exists in another instance?\r\n(Note: You cannot duplicate names across instances- requires unique name)"); + //You can debug using commandline + //>sqllocaldb info mssqllocaldb + + //https://docs.microsoft.com/en-us/sql/tools/sqllocaldb-utility?view=sql-server-ver15 + + string url = @"https://docs.microsoft.com/en-us/sql/relational-databases/express-localdb-instance-apis/command-line-management-tool-sqllocaldb-exe?view=sql-server-ver15"; + Process.Start(url); + + Application.Exit(); + } + + MessageBox.Show($" A New empty Local Database has been created successfully!\r\n\r\nSQLLOCALDB:{InstanceName}\r\nDATABASE:{DatabaseName}"); + } + } + } + + static bool CreateLocalDBInstance(string InstanceName) + { + // Lists all instances + // >sqllocaldb info + + // Start the child process. + Process p = new Process(); + // Redirect the output stream of the child process. + p.StartInfo.UseShellExecute = false; + p.StartInfo.RedirectStandardOutput = true; + p.StartInfo.FileName = "cmd.exe"; + p.StartInfo.Arguments = $"/C sqllocaldb c {InstanceName}"; //Create Local Db Instance + p.StartInfo.CreateNoWindow = true; + p.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; + p.Start(); + string sOutput = p.StandardOutput.ReadToEnd(); + p.WaitForExit(); + + //If LocalDb is not installed then it will return that 'sqllocaldb' is not recognized as an internal or external command operable program or batch file. + if (sOutput == null || sOutput.Trim().Length == 0 || sOutput.Contains("not recognized")) + return false; + if (sOutput.ToLower().Contains(InstanceName)) + return true; + return false; + } + + public static bool CheckDatabaseExists(string connectionString, string databaseName) + { + + using (var connection = new SqlConnection(connectionString)) + { + using (var command = new SqlCommand($"SELECT db_id('{databaseName}')", connection)) + { + connection.Open(); + var retval = command.ExecuteScalar(); + + return (retval != DBNull.Value); + } + } + } + } +} \ No newline at end of file diff --git a/src/Examples/EF6/E1_ModelPerson/Properties/AssemblyInfo.cs b/src/Examples/EF6/E1_ModelPerson/Properties/AssemblyInfo.cs new file mode 100644 index 000000000..d068d5197 --- /dev/null +++ b/src/Examples/EF6/E1_ModelPerson/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("Example 1 Person")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("")] +[assembly: AssemblyCopyright("Copyright © 2021")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("b0c345bb-4b38-44ce-8d42-3e00545347ba")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/src/Examples/EF6/E1_ModelPerson/Properties/Resources.Designer.cs b/src/Examples/EF6/E1_ModelPerson/Properties/Resources.Designer.cs new file mode 100644 index 000000000..9cad178f4 --- /dev/null +++ b/src/Examples/EF6/E1_ModelPerson/Properties/Resources.Designer.cs @@ -0,0 +1,63 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace Ex1_Person.Properties { + using System; + + + /// + /// A strongly-typed resource class, for looking up localized strings, etc. + /// + // This class was auto-generated by the StronglyTypedResourceBuilder + // class via a tool like ResGen or Visual Studio. + // To add or remove a member, edit your .ResX file then rerun ResGen + // with the /str option, or rebuild your VS project. + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + internal class Resources { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal Resources() { + } + + /// + /// Returns the cached ResourceManager instance used by this class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Resources.ResourceManager ResourceManager { + get { + if (object.ReferenceEquals(resourceMan, null)) { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Ex1_Person.Properties.Resources", typeof(Resources).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// + /// Overrides the current thread's CurrentUICulture property for all + /// resource lookups using this strongly typed resource class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Globalization.CultureInfo Culture { + get { + return resourceCulture; + } + set { + resourceCulture = value; + } + } + } +} diff --git a/src/Examples/EF6/E1_ModelPerson/Properties/Resources.resx b/src/Examples/EF6/E1_ModelPerson/Properties/Resources.resx new file mode 100644 index 000000000..af7dbebba --- /dev/null +++ b/src/Examples/EF6/E1_ModelPerson/Properties/Resources.resx @@ -0,0 +1,117 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/src/Examples/EF6/E1_ModelPerson/Properties/Settings.Designer.cs b/src/Examples/EF6/E1_ModelPerson/Properties/Settings.Designer.cs new file mode 100644 index 000000000..da60f0f03 --- /dev/null +++ b/src/Examples/EF6/E1_ModelPerson/Properties/Settings.Designer.cs @@ -0,0 +1,26 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace Ex1_Person.Properties { + + + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "16.10.0.0")] + internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { + + private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); + + public static Settings Default { + get { + return defaultInstance; + } + } + } +} diff --git a/src/Examples/EF6/E1_ModelPerson/Properties/Settings.settings b/src/Examples/EF6/E1_ModelPerson/Properties/Settings.settings new file mode 100644 index 000000000..39645652a --- /dev/null +++ b/src/Examples/EF6/E1_ModelPerson/Properties/Settings.settings @@ -0,0 +1,7 @@ + + + + + + + diff --git a/src/Examples/EF6/E1_ModelPerson/frmPerson.Designer.cs b/src/Examples/EF6/E1_ModelPerson/frmPerson.Designer.cs new file mode 100644 index 000000000..ca19cc9bc --- /dev/null +++ b/src/Examples/EF6/E1_ModelPerson/frmPerson.Designer.cs @@ -0,0 +1,103 @@ + +namespace Ex1_Person +{ + partial class frmPerson + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + this.btnTestPerson = new System.Windows.Forms.Button(); + this.txtConnection = new System.Windows.Forms.TextBox(); + this.label1 = new System.Windows.Forms.Label(); + this.txtDebug = new System.Windows.Forms.TextBox(); + this.SuspendLayout(); + // + // btnTestPerson + // + this.btnTestPerson.Location = new System.Drawing.Point(36, 117); + this.btnTestPerson.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + this.btnTestPerson.Name = "btnTestPerson"; + this.btnTestPerson.Size = new System.Drawing.Size(170, 63); + this.btnTestPerson.TabIndex = 0; + this.btnTestPerson.Text = "Test Person"; + this.btnTestPerson.UseVisualStyleBackColor = true; + this.btnTestPerson.Click += new System.EventHandler(this.btnTestPerson_Click); + // + // txtConnection + // + this.txtConnection.Location = new System.Drawing.Point(36, 55); + this.txtConnection.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + this.txtConnection.Name = "txtConnection"; + this.txtConnection.Size = new System.Drawing.Size(734, 26); + this.txtConnection.TabIndex = 1; + this.txtConnection.Text = "..."; + // + // label1 + // + this.label1.AutoSize = true; + this.label1.Location = new System.Drawing.Point(36, 31); + this.label1.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); + this.label1.Name = "label1"; + this.label1.Size = new System.Drawing.Size(167, 20); + this.label1.TabIndex = 2; + this.label1.Text = "Sql Server Connection"; + // + // txtDebug + // + this.txtDebug.Location = new System.Drawing.Point(350, 117); + this.txtDebug.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + this.txtDebug.Multiline = true; + this.txtDebug.Name = "txtDebug"; + this.txtDebug.Size = new System.Drawing.Size(421, 266); + this.txtDebug.TabIndex = 3; + // + // frmPerson + // + this.AutoScaleDimensions = new System.Drawing.SizeF(9F, 20F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(790, 398); + this.Controls.Add(this.txtDebug); + this.Controls.Add(this.label1); + this.Controls.Add(this.txtConnection); + this.Controls.Add(this.btnTestPerson); + this.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + this.Name = "frmPerson"; + this.Text = "Ex 1: Simple Table - Entity Framework Examples: Using Visual Designer"; + this.Load += new System.EventHandler(this.Form1_Load); + this.ResumeLayout(false); + this.PerformLayout(); + + } + + #endregion + + private System.Windows.Forms.Button btnTestPerson; + private System.Windows.Forms.TextBox txtConnection; + private System.Windows.Forms.Label label1; + private System.Windows.Forms.TextBox txtDebug; + } +} + diff --git a/src/Examples/EF6/E1_ModelPerson/frmPerson.cs b/src/Examples/EF6/E1_ModelPerson/frmPerson.cs new file mode 100644 index 000000000..1905ba06f --- /dev/null +++ b/src/Examples/EF6/E1_ModelPerson/frmPerson.cs @@ -0,0 +1,102 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Data.Entity; +using System.Data.Entity.Validation; +using System.Drawing; +using System.Globalization; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace Ex1_Person +{ + public partial class frmPerson : Form + { + //How to use Entity Framework + //https://docs.microsoft.com/en-us/ef/ef6/ + + public frmPerson() + { + InitializeComponent(); + } + + private void Form1_Load(object sender, EventArgs e) + { + using (PersonModel context = new PersonModel()) + { + txtConnection.Text = context.Database.Connection.ConnectionString; + } + + } + + private void btnTestPerson_Click(object sender, EventArgs e) + { + TestPerson(); + } + + private void TestPerson() + { + txtDebug.Text = "TestPerson()\r\n"; + + using (PersonModel context = new PersonModel()) + { + // Perform data access using the context + context.Database.Log = Console.Write; + + context.Database.Delete(); + txtDebug.Text += "Deleted DB\r\n"; + + context.Database.CreateIfNotExists(); + txtDebug.Text += "Created DB\r\n"; + + Person person = new Person(); + person.FirstName = "Bob"; + person.MiddleName = "James"; + person.LastName = "Smith"; + person.Phone = "555-123-321"; + CultureInfo culture = new CultureInfo("en-AU"); + person.DOB = Convert.ToDateTime("6/12/70",culture); + + context.People.Add(person); + + + // This Exception handler helps to describe what went wrong with the EF database save. + // It decodes why the data did not comply with defined database field structure. e.g too long or wrong type. + try + { + context.SaveChanges(); + } + catch (System.Data.Entity.Validation.DbEntityValidationException dbEx) + { + Exception raise = dbEx; + foreach (DbEntityValidationResult validationErrors in dbEx.EntityValidationErrors) + { + foreach (DbValidationError validationError in validationErrors.ValidationErrors) + { + string message = string.Format("{0}:{1}", + validationErrors.Entry.Entity.ToString(), + validationError.ErrorMessage); + // raise a new exception nesting the current instance as InnerException + raise = new InvalidOperationException(message, raise); + } + } + throw raise; + } + + //Read it back + DbSet people = context.People; + + foreach (Person p in people) + txtDebug.Text += String.Format("{0} {1} {2} {3} {4}", p.Id, p.FirstName, p.MiddleName, p.LastName, p.Phone) + "\r\n"; + } + } + + private void button1_Click(object sender, EventArgs e) + { + + } + } +} diff --git a/src/Examples/EF6/E1_ModelPerson/frmPerson.resx b/src/Examples/EF6/E1_ModelPerson/frmPerson.resx new file mode 100644 index 000000000..1af7de150 --- /dev/null +++ b/src/Examples/EF6/E1_ModelPerson/frmPerson.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/src/Examples/EF6/E1_ModelPerson/unused/Ex3_ModelOne2Many.cs b/src/Examples/EF6/E1_ModelPerson/unused/Ex3_ModelOne2Many.cs new file mode 100644 index 000000000..6153a7d78 --- /dev/null +++ b/src/Examples/EF6/E1_ModelPerson/unused/Ex3_ModelOne2Many.cs @@ -0,0 +1 @@ + diff --git a/src/Examples/EF6/E1_ModelPerson/unused/Ex3_ModelOne2Many.efmodel b/src/Examples/EF6/E1_ModelPerson/unused/Ex3_ModelOne2Many.efmodel new file mode 100644 index 000000000..cceeff9ed --- /dev/null +++ b/src/Examples/EF6/E1_ModelPerson/unused/Ex3_ModelOne2Many.efmodel @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/Examples/EF6/E1_ModelPerson/unused/Ex3_ModelOne2Many.efmodel.diagramx b/src/Examples/EF6/E1_ModelPerson/unused/Ex3_ModelOne2Many.efmodel.diagramx new file mode 100644 index 000000000..13694409e --- /dev/null +++ b/src/Examples/EF6/E1_ModelPerson/unused/Ex3_ModelOne2Many.efmodel.diagramx @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + diff --git a/src/Examples/EF6/E1_ModelPerson/unused/Ex3_ModelOne2Many.tt b/src/Examples/EF6/E1_ModelPerson/unused/Ex3_ModelOne2Many.tt new file mode 100644 index 000000000..99dcb7441 --- /dev/null +++ b/src/Examples/EF6/E1_ModelPerson/unused/Ex3_ModelOne2Many.tt @@ -0,0 +1,74 @@ +<#@ template inherits="Microsoft.VisualStudio.TextTemplating.VSHost.ModelingTextTransformation" debug="true" + hostSpecific="true" language="C#" compilerOptions="/langversion:latest"#> +<#@ CleanupBehavior processor="T4VSHost" CleanupAfterProcessingtemplate="true" #> +<#@ assembly name="System.Data.Entity.Design.dll" +#><#@ assembly name="EnvDTE" +#><#@ include file="EFDesigner.ttinclude" once="true" +#><#@ output extension=".cs" +#><#@ import namespace="System.Linq" +#><#@ import namespace="System" +#><#@ import namespace="System.Data.Entity.Design.PluralizationServices" +#><#@ import namespace="System.Globalization" +#><#@ import namespace="Sawczyn.EFDesigner.EFModel" +#><#@ EFModel processor="EFModelDirectiveProcessor" requires="FileName='ModelOne2Many.efmodel'" +#><# + Manager manager = Manager.Create(Host, GenerationEnvironment); + manager.FileNameMarker = ModelRoot.FileNameMarker; + + if (ModelRoot.Classes.Any()) + { + manager.StartHeader(false); + Output("//------------------------------------------------------------------------------"); + Output("// "); + Output("// This code was generated from a template."); + Output("//"); + Output("// Manual changes to this file may cause unexpected behavior in your application."); + Output("// Manual changes to this file will be overwritten if the code is regenerated."); + Output("//"); + Output("// Produced by Entity Framework Visual Editor v" + ModelRoot.DSLVersion); + Output("// Source: https://github.com/msawczyn/EFDesigner"); + Output("// Visual Studio Marketplace: https://marketplace.visualstudio.com/items?itemName=michaelsawczyn.EFDesigner"); + Output("// Documentation: https://msawczyn.github.io/EFDesigner/"); + Output("// License (MIT): https://github.com/msawczyn/EFDesigner/blob/master/LICENSE"); + Output("// "); + Output("//------------------------------------------------------------------------------"); + NL(); + + EFModelGenerator generator; + + switch (ModelRoot.EntityFrameworkVersion) + { + case EFVersion.EF6: + { + generator = new EF6ModelGenerator(this); + break; + } + + case EFVersion.EFCore: + { + switch ((int)ModelRoot.GetEntityFrameworkPackageVersionNum()) + { + case 2: + generator = new EFCore2ModelGenerator(this); + break; + + case 3: + generator = new EFCore3ModelGenerator(this); + break; + + default: + generator = new EFCore5ModelGenerator(this); + break; + } + break; + } + + default: + throw new InvalidOperationException("Unsupported Entity Framework version"); + } + + generator.Generate(manager); + } + + manager.Process(true); +#> \ No newline at end of file diff --git a/src/Examples/EF6/E1_ModelPerson/unused/Ex3_ModelOne2Many1.cs b/src/Examples/EF6/E1_ModelPerson/unused/Ex3_ModelOne2Many1.cs new file mode 100644 index 000000000..2edc99e3e --- /dev/null +++ b/src/Examples/EF6/E1_ModelPerson/unused/Ex3_ModelOne2Many1.cs @@ -0,0 +1 @@ +ErrorGeneratingOutput \ No newline at end of file diff --git a/src/Examples/EF6/EF6.sln b/src/Examples/EF6/EF6.sln new file mode 100644 index 000000000..56ae5ce05 --- /dev/null +++ b/src/Examples/EF6/EF6.sln @@ -0,0 +1,55 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.31729.503 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Ex1_Person", "E1_ModelPerson\Ex1_Person.csproj", "{B0C345BB-4B38-44CE-8D42-3E00545347BA}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Ex2_ModelOne2One", "Ex2_ModelOne2One\Ex2_ModelOne2One.csproj", "{357AB96C-3EA3-4F76-B416-B265661E8BB6}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Ex3_ModelOnetoMany", "Ex3_ModelManytoMany\Ex3_ModelOnetoMany.csproj", "{CD767834-7004-444D-B7D8-58AC359ED441}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Ex4_ModelInvoice", "Ex4_ModelInvoice\Ex4_ModelInvoice.csproj", "{2B46097A-AE7A-4F87-A7D8-EC7F9865A681}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Ex6_CRM", "Ex5_Store\Ex6_CRM.csproj", "{9E4E33FD-1644-4AD1-9F6C-42389F7D3647}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Ex5_Course", "Ex6_Course\Ex5_Course.csproj", "{BF56F02E-DCEB-413D-8DE6-A1FFA71870A8}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {B0C345BB-4B38-44CE-8D42-3E00545347BA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {B0C345BB-4B38-44CE-8D42-3E00545347BA}.Debug|Any CPU.Build.0 = Debug|Any CPU + {B0C345BB-4B38-44CE-8D42-3E00545347BA}.Release|Any CPU.ActiveCfg = Release|Any CPU + {B0C345BB-4B38-44CE-8D42-3E00545347BA}.Release|Any CPU.Build.0 = Release|Any CPU + {357AB96C-3EA3-4F76-B416-B265661E8BB6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {357AB96C-3EA3-4F76-B416-B265661E8BB6}.Debug|Any CPU.Build.0 = Debug|Any CPU + {357AB96C-3EA3-4F76-B416-B265661E8BB6}.Release|Any CPU.ActiveCfg = Release|Any CPU + {357AB96C-3EA3-4F76-B416-B265661E8BB6}.Release|Any CPU.Build.0 = Release|Any CPU + {CD767834-7004-444D-B7D8-58AC359ED441}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {CD767834-7004-444D-B7D8-58AC359ED441}.Debug|Any CPU.Build.0 = Debug|Any CPU + {CD767834-7004-444D-B7D8-58AC359ED441}.Release|Any CPU.ActiveCfg = Release|Any CPU + {CD767834-7004-444D-B7D8-58AC359ED441}.Release|Any CPU.Build.0 = Release|Any CPU + {2B46097A-AE7A-4F87-A7D8-EC7F9865A681}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {2B46097A-AE7A-4F87-A7D8-EC7F9865A681}.Debug|Any CPU.Build.0 = Debug|Any CPU + {2B46097A-AE7A-4F87-A7D8-EC7F9865A681}.Release|Any CPU.ActiveCfg = Release|Any CPU + {2B46097A-AE7A-4F87-A7D8-EC7F9865A681}.Release|Any CPU.Build.0 = Release|Any CPU + {9E4E33FD-1644-4AD1-9F6C-42389F7D3647}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {9E4E33FD-1644-4AD1-9F6C-42389F7D3647}.Debug|Any CPU.Build.0 = Debug|Any CPU + {9E4E33FD-1644-4AD1-9F6C-42389F7D3647}.Release|Any CPU.ActiveCfg = Release|Any CPU + {9E4E33FD-1644-4AD1-9F6C-42389F7D3647}.Release|Any CPU.Build.0 = Release|Any CPU + {BF56F02E-DCEB-413D-8DE6-A1FFA71870A8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {BF56F02E-DCEB-413D-8DE6-A1FFA71870A8}.Debug|Any CPU.Build.0 = Debug|Any CPU + {BF56F02E-DCEB-413D-8DE6-A1FFA71870A8}.Release|Any CPU.ActiveCfg = Release|Any CPU + {BF56F02E-DCEB-413D-8DE6-A1FFA71870A8}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {27F1FF2D-7DAD-496C-889E-651C12319E4B} + EndGlobalSection +EndGlobal diff --git a/src/Examples/EF6/Ex2_ModelOne2One/App.config b/src/Examples/EF6/Ex2_ModelOne2One/App.config new file mode 100644 index 000000000..193aecc67 --- /dev/null +++ b/src/Examples/EF6/Ex2_ModelOne2One/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/src/Examples/EF6/Ex2_ModelOne2One/EFModelOne2One.cs b/src/Examples/EF6/Ex2_ModelOne2One/EFModelOne2One.cs new file mode 100644 index 000000000..6153a7d78 --- /dev/null +++ b/src/Examples/EF6/Ex2_ModelOne2One/EFModelOne2One.cs @@ -0,0 +1 @@ + diff --git a/src/Examples/EF6/Ex2_ModelOne2One/EFModelOne2One.efmodel b/src/Examples/EF6/Ex2_ModelOne2One/EFModelOne2One.efmodel new file mode 100644 index 000000000..0b171602e --- /dev/null +++ b/src/Examples/EF6/Ex2_ModelOne2One/EFModelOne2One.efmodel @@ -0,0 +1,52 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/Examples/EF6/Ex2_ModelOne2One/EFModelOne2One.efmodel.diagramx b/src/Examples/EF6/Ex2_ModelOne2One/EFModelOne2One.efmodel.diagramx new file mode 100644 index 000000000..444ace137 --- /dev/null +++ b/src/Examples/EF6/Ex2_ModelOne2One/EFModelOne2One.efmodel.diagramx @@ -0,0 +1,40 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/Examples/EF6/Ex2_ModelOne2One/EFModelOne2One.tt b/src/Examples/EF6/Ex2_ModelOne2One/EFModelOne2One.tt new file mode 100644 index 000000000..39e9eaf4c --- /dev/null +++ b/src/Examples/EF6/Ex2_ModelOne2One/EFModelOne2One.tt @@ -0,0 +1,74 @@ +<#@ template inherits="Microsoft.VisualStudio.TextTemplating.VSHost.ModelingTextTransformation" debug="true" + hostSpecific="true" language="C#" compilerOptions="/langversion:latest"#> +<#@ CleanupBehavior processor="T4VSHost" CleanupAfterProcessingtemplate="true" #> +<#@ assembly name="System.Data.Entity.Design.dll" +#><#@ assembly name="EnvDTE" +#><#@ include file="EFDesigner.ttinclude" once="true" +#><#@ output extension=".cs" +#><#@ import namespace="System.Linq" +#><#@ import namespace="System" +#><#@ import namespace="System.Data.Entity.Design.PluralizationServices" +#><#@ import namespace="System.Globalization" +#><#@ import namespace="Sawczyn.EFDesigner.EFModel" +#><#@ EFModel processor="EFModelDirectiveProcessor" requires="FileName='EFModelOne2One.efmodel'" +#><# + Manager manager = Manager.Create(Host, GenerationEnvironment); + manager.FileNameMarker = ModelRoot.FileNameMarker; + + if (ModelRoot.Classes.Any()) + { + manager.StartHeader(false); + Output("//------------------------------------------------------------------------------"); + Output("// "); + Output("// This code was generated from a template."); + Output("//"); + Output("// Manual changes to this file may cause unexpected behavior in your application."); + Output("// Manual changes to this file will be overwritten if the code is regenerated."); + Output("//"); + Output("// Produced by Entity Framework Visual Editor v" + ModelRoot.DSLVersion); + Output("// Source: https://github.com/msawczyn/EFDesigner"); + Output("// Visual Studio Marketplace: https://marketplace.visualstudio.com/items?itemName=michaelsawczyn.EFDesigner"); + Output("// Documentation: https://msawczyn.github.io/EFDesigner/"); + Output("// License (MIT): https://github.com/msawczyn/EFDesigner/blob/master/LICENSE"); + Output("// "); + Output("//------------------------------------------------------------------------------"); + NL(); + + EFModelGenerator generator; + + switch (ModelRoot.EntityFrameworkVersion) + { + case EFVersion.EF6: + { + generator = new EF6ModelGenerator(this); + break; + } + + case EFVersion.EFCore: + { + switch ((int)ModelRoot.GetEntityFrameworkPackageVersionNum()) + { + case 2: + generator = new EFCore2ModelGenerator(this); + break; + + case 3: + generator = new EFCore3ModelGenerator(this); + break; + + default: + generator = new EFCore5ModelGenerator(this); + break; + } + break; + } + + default: + throw new InvalidOperationException("Unsupported Entity Framework version"); + } + + generator.Generate(manager); + } + + manager.Process(true); +#> \ No newline at end of file diff --git a/src/Examples/EF6/Ex2_ModelOne2One/Ex2_ModelOne2One.cs b/src/Examples/EF6/Ex2_ModelOne2One/Ex2_ModelOne2One.cs new file mode 100644 index 000000000..2edc99e3e --- /dev/null +++ b/src/Examples/EF6/Ex2_ModelOne2One/Ex2_ModelOne2One.cs @@ -0,0 +1 @@ +ErrorGeneratingOutput \ No newline at end of file diff --git a/src/Examples/EF6/Ex2_ModelOne2One/Ex2_ModelOne2One.csproj b/src/Examples/EF6/Ex2_ModelOne2One/Ex2_ModelOne2One.csproj new file mode 100644 index 000000000..2895a8204 --- /dev/null +++ b/src/Examples/EF6/Ex2_ModelOne2One/Ex2_ModelOne2One.csproj @@ -0,0 +1,111 @@ + + + + + Debug + AnyCPU + {357AB96C-3EA3-4F76-B416-B265661E8BB6} + WinExe + Ex2_ModelOne2One + Ex2_ModelOne2One + v4.8 + 512 + true + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + True + True + EFModelOne2One.tt + + + Form + + + FrmOne2One.cs + + + + + + + + + + FrmOne2One.cs + + + ResXFileCodeGenerator + Resources.Designer.cs + Designer + + + True + Resources.resx + + + + EFModelOne2One.efmodel + + + SettingsSingleFileGenerator + Settings.Designer.cs + + + True + Settings.settings + True + + + + + + + + 6.4.4 + + + + + TextTemplatingFileGenerator + EFModelOne2One.cs + + + + + + + \ No newline at end of file diff --git a/src/Examples/EF6/Ex2_ModelOne2One/Ex2_ModelOne2One.efmodel b/src/Examples/EF6/Ex2_ModelOne2One/Ex2_ModelOne2One.efmodel new file mode 100644 index 000000000..3073ff152 --- /dev/null +++ b/src/Examples/EF6/Ex2_ModelOne2One/Ex2_ModelOne2One.efmodel @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/Examples/EF6/Ex2_ModelOne2One/Ex2_ModelOne2One.efmodel.diagramx b/src/Examples/EF6/Ex2_ModelOne2One/Ex2_ModelOne2One.efmodel.diagramx new file mode 100644 index 000000000..fdbab50e4 --- /dev/null +++ b/src/Examples/EF6/Ex2_ModelOne2One/Ex2_ModelOne2One.efmodel.diagramx @@ -0,0 +1,34 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/Examples/EF6/Ex2_ModelOne2One/Ex2_ModelOne2One.tt b/src/Examples/EF6/Ex2_ModelOne2One/Ex2_ModelOne2One.tt new file mode 100644 index 000000000..f6234b7a8 --- /dev/null +++ b/src/Examples/EF6/Ex2_ModelOne2One/Ex2_ModelOne2One.tt @@ -0,0 +1,74 @@ +<#@ template inherits="Microsoft.VisualStudio.TextTemplating.VSHost.ModelingTextTransformation" debug="true" + hostSpecific="true" language="C#" compilerOptions="/langversion:latest"#> +<#@ CleanupBehavior processor="T4VSHost" CleanupAfterProcessingtemplate="true" #> +<#@ assembly name="System.Data.Entity.Design.dll" +#><#@ assembly name="EnvDTE" +#><#@ include file="EFDesigner.ttinclude" once="true" +#><#@ output extension=".cs" +#><#@ import namespace="System.Linq" +#><#@ import namespace="System" +#><#@ import namespace="System.Data.Entity.Design.PluralizationServices" +#><#@ import namespace="System.Globalization" +#><#@ import namespace="Sawczyn.EFDesigner.EFModel" +#><#@ EFModel processor="EFModelDirectiveProcessor" requires="FileName='Ex2_ModelOne2One.efmodel'" +#><# + Manager manager = Manager.Create(Host, GenerationEnvironment); + manager.FileNameMarker = ModelRoot.FileNameMarker; + + if (ModelRoot.Classes.Any()) + { + manager.StartHeader(false); + Output("//------------------------------------------------------------------------------"); + Output("// "); + Output("// This code was generated from a template."); + Output("//"); + Output("// Manual changes to this file may cause unexpected behavior in your application."); + Output("// Manual changes to this file will be overwritten if the code is regenerated."); + Output("//"); + Output("// Produced by Entity Framework Visual Editor v" + ModelRoot.DSLVersion); + Output("// Source: https://github.com/msawczyn/EFDesigner"); + Output("// Visual Studio Marketplace: https://marketplace.visualstudio.com/items?itemName=michaelsawczyn.EFDesigner"); + Output("// Documentation: https://msawczyn.github.io/EFDesigner/"); + Output("// License (MIT): https://github.com/msawczyn/EFDesigner/blob/master/LICENSE"); + Output("// "); + Output("//------------------------------------------------------------------------------"); + NL(); + + EFModelGenerator generator; + + switch (ModelRoot.EntityFrameworkVersion) + { + case EFVersion.EF6: + { + generator = new EF6ModelGenerator(this); + break; + } + + case EFVersion.EFCore: + { + switch ((int)ModelRoot.GetEntityFrameworkPackageVersionNum()) + { + case 2: + generator = new EFCore2ModelGenerator(this); + break; + + case 3: + generator = new EFCore3ModelGenerator(this); + break; + + default: + generator = new EFCore5ModelGenerator(this); + break; + } + break; + } + + default: + throw new InvalidOperationException("Unsupported Entity Framework version"); + } + + generator.Generate(manager); + } + + manager.Process(true); +#> \ No newline at end of file diff --git a/src/Examples/EF6/Ex2_ModelOne2One/Ex2_ModelOne2One1.cs b/src/Examples/EF6/Ex2_ModelOne2One/Ex2_ModelOne2One1.cs new file mode 100644 index 000000000..6153a7d78 --- /dev/null +++ b/src/Examples/EF6/Ex2_ModelOne2One/Ex2_ModelOne2One1.cs @@ -0,0 +1 @@ + diff --git a/src/Examples/EF6/Ex2_ModelOne2One/FrmOne2One.Designer.cs b/src/Examples/EF6/Ex2_ModelOne2One/FrmOne2One.Designer.cs new file mode 100644 index 000000000..43c3acb8d --- /dev/null +++ b/src/Examples/EF6/Ex2_ModelOne2One/FrmOne2One.Designer.cs @@ -0,0 +1,102 @@ + +namespace Ex2_ModelOne2One +{ + partial class FrmOne2One + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + this.txtDebug = new System.Windows.Forms.TextBox(); + this.label1 = new System.Windows.Forms.Label(); + this.txtConnection = new System.Windows.Forms.TextBox(); + this.btnTestOne2One = new System.Windows.Forms.Button(); + this.SuspendLayout(); + // + // txtDebug + // + this.txtDebug.Location = new System.Drawing.Point(356, 134); + this.txtDebug.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + this.txtDebug.Multiline = true; + this.txtDebug.Name = "txtDebug"; + this.txtDebug.Size = new System.Drawing.Size(421, 266); + this.txtDebug.TabIndex = 8; + // + // label1 + // + this.label1.AutoSize = true; + this.label1.Location = new System.Drawing.Point(42, 48); + this.label1.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); + this.label1.Name = "label1"; + this.label1.Size = new System.Drawing.Size(167, 20); + this.label1.TabIndex = 7; + this.label1.Text = "Sql Server Connection"; + // + // txtConnection + // + this.txtConnection.Location = new System.Drawing.Point(42, 72); + this.txtConnection.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + this.txtConnection.Name = "txtConnection"; + this.txtConnection.Size = new System.Drawing.Size(734, 26); + this.txtConnection.TabIndex = 6; + this.txtConnection.Text = "..."; + // + // btnTestOne2One + // + this.btnTestOne2One.Location = new System.Drawing.Point(42, 134); + this.btnTestOne2One.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + this.btnTestOne2One.Name = "btnTestOne2One"; + this.btnTestOne2One.Size = new System.Drawing.Size(170, 63); + this.btnTestOne2One.TabIndex = 5; + this.btnTestOne2One.Text = "Test One to One"; + this.btnTestOne2One.UseVisualStyleBackColor = true; + this.btnTestOne2One.Click += new System.EventHandler(this.btnTestOne2One_Click); + // + // FrmOne2One + // + this.AutoScaleDimensions = new System.Drawing.SizeF(9F, 20F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(820, 451); + this.Controls.Add(this.txtDebug); + this.Controls.Add(this.label1); + this.Controls.Add(this.txtConnection); + this.Controls.Add(this.btnTestOne2One); + this.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + this.Name = "FrmOne2One"; + this.Text = "Ex 2: One to One - Person & Address"; + this.Load += new System.EventHandler(this.Form1_Load); + this.ResumeLayout(false); + this.PerformLayout(); + + } + + #endregion + private System.Windows.Forms.TextBox txtDebug; + private System.Windows.Forms.Label label1; + private System.Windows.Forms.TextBox txtConnection; + private System.Windows.Forms.Button btnTestOne2One; + } +} + diff --git a/src/Examples/EF6/Ex2_ModelOne2One/FrmOne2One.cs b/src/Examples/EF6/Ex2_ModelOne2One/FrmOne2One.cs new file mode 100644 index 000000000..8083846da --- /dev/null +++ b/src/Examples/EF6/Ex2_ModelOne2One/FrmOne2One.cs @@ -0,0 +1,105 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Data.Entity.Validation; +using System.Drawing; +using System.Globalization; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace Ex2_ModelOne2One +{ + public partial class FrmOne2One : Form + { + //https://medium.com/@emekadc/how-to-implement-one-to-one-one-to-many-and-many-to-many-relationships-when-designing-a-database-9da2de684710 + + public FrmOne2One() + { + InitializeComponent(); + } + + private void Form1_Load(object sender, EventArgs e) + { + using (EFModelOne2One context = new EFModelOne2One()) + { + txtConnection.Text = context.Database.Connection.ConnectionString; + } + } + + private void btnTestOne2One_Click(object sender, EventArgs e) + { + TestOne2One(); + } + + void TestOne2One() + { + txtDebug.Text = "TestOne2One()\r\n"; + + using (EFModelOne2One context = new EFModelOne2One()) + { + // Perform data access using the context + context.Database.Log = Console.Write; + + context.Database.Delete(); + txtDebug.Text += "Deleted DB\r\n"; + + context.Database.CreateIfNotExists(); + txtDebug.Text += "Created DB\r\n"; + + var person = context.People.Create(); + var address = context.Address.Create(); + + person.FirstName = "Bob"; + person.MiddleName = "James"; + person.LastName = "Smith"; + person.Phone = "555-123-321"; + CultureInfo culture = new CultureInfo("en-AU"); + person.DOB = Convert.ToDateTime("6/12/70", culture); + + address.Number = "1"; + address.StreetLine1 = "High St"; + address.City = "Perth"; + address.Country = "Australia"; + + //One to One + person.Address = address; + + context.People.Add(person); + + try + { + context.SaveChanges(); + } + catch (System.Data.Entity.Validation.DbEntityValidationException dbEx) + { + Exception raise = dbEx; + foreach (DbEntityValidationResult validationErrors in dbEx.EntityValidationErrors) + { + foreach (DbValidationError validationError in validationErrors.ValidationErrors) + { + string message = string.Format("{0}:{1}", + validationErrors.Entry.Entity.ToString(), + validationError.ErrorMessage); + // raise a new exception nesting the current instance as InnerException + raise = new InvalidOperationException(message, raise); + } + } + throw raise; + } + + //Read it back + var items = context.People; + + foreach (var x in items) + { + txtDebug.Text += String.Format("{0} {1} {2} {3} {4} ", x.PersonId, x.FirstName, x.MiddleName, x.LastName, x.Phone) + "\r\n"; + txtDebug.Text += String.Format("{0} {1} {2} {3} {4} {5} ", x.Address.Number, x.Address.StreetLine1, x.Address.StreetLine2, x.Address.StreetType, x.Address.City, x.Address.PostalCode ) + "\r\n"; + } + + } + } + } +} diff --git a/src/Examples/EF6/Ex2_ModelOne2One/FrmOne2One.resx b/src/Examples/EF6/Ex2_ModelOne2One/FrmOne2One.resx new file mode 100644 index 000000000..1af7de150 --- /dev/null +++ b/src/Examples/EF6/Ex2_ModelOne2One/FrmOne2One.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/src/Examples/EF6/Ex2_ModelOne2One/Generated_Ex2_ModelOne2One/Adress.generated.cs b/src/Examples/EF6/Ex2_ModelOne2One/Generated_Ex2_ModelOne2One/Adress.generated.cs new file mode 100644 index 000000000..904c6bba5 --- /dev/null +++ b/src/Examples/EF6/Ex2_ModelOne2One/Generated_Ex2_ModelOne2One/Adress.generated.cs @@ -0,0 +1,94 @@ +//------------------------------------------------------------------------------ +// +// This code was generated from a template. +// +// Manual changes to this file may cause unexpected behavior in your application. +// Manual changes to this file will be overwritten if the code is regenerated. +// +// Produced by Entity Framework Visual Editor v3.0.7.2 +// Source: https://github.com/msawczyn/EFDesigner +// Visual Studio Marketplace: https://marketplace.visualstudio.com/items?itemName=michaelsawczyn.EFDesigner +// Documentation: https://msawczyn.github.io/EFDesigner/ +// License (MIT): https://github.com/msawczyn/EFDesigner/blob/master/LICENSE +// +//------------------------------------------------------------------------------ + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using System.Linq; +using System.Runtime.CompilerServices; + +namespace EF6_Ex2 +{ + public partial class Adress + { + partial void Init(); + + /// + /// Default constructor + /// + public Adress() + { + Init(); + } + + /// + /// Public constructor with required data + /// + /// + public Adress(global::EF6_Ex2.Person person) + { + if (person == null) throw new ArgumentNullException(nameof(person)); + this.Person = person; + person.Entity1.Add(this); + + Init(); + } + + /// + /// Static create function (for use in LINQ queries, etc.) + /// + /// + public static Adress Create(global::EF6_Ex2.Person person) + { + return new Adress(person); + } + + /************************************************************************* + * Properties + *************************************************************************/ + + /// + /// Identity, Indexed, Required + /// Unique identifier + /// + [Key] + [Required] + [System.ComponentModel.Description("Unique identifier")] + public long Id { get; set; } + + /// + /// Required + /// Concurrency token + /// + [ConcurrencyCheck] + [Required] + [System.ComponentModel.Description("Concurrency token")] + public byte[] Timestamp { get; set; } + + /************************************************************************* + * Navigation properties + *************************************************************************/ + + /// + /// Required + /// + public virtual global::EF6_Ex2.Person Person { get; set; } + + } +} + diff --git a/src/Examples/EF6/Ex2_ModelOne2One/Generated_Ex2_ModelOne2One/ModelOne2One.generated.cs b/src/Examples/EF6/Ex2_ModelOne2One/Generated_Ex2_ModelOne2One/ModelOne2One.generated.cs new file mode 100644 index 000000000..e7304e5a0 --- /dev/null +++ b/src/Examples/EF6/Ex2_ModelOne2One/Generated_Ex2_ModelOne2One/ModelOne2One.generated.cs @@ -0,0 +1,162 @@ +//------------------------------------------------------------------------------ +// +// This code was generated from a template. +// +// Manual changes to this file may cause unexpected behavior in your application. +// Manual changes to this file will be overwritten if the code is regenerated. +// +// Produced by Entity Framework Visual Editor v3.0.7.2 +// Source: https://github.com/msawczyn/EFDesigner +// Visual Studio Marketplace: https://marketplace.visualstudio.com/items?itemName=michaelsawczyn.EFDesigner +// Documentation: https://msawczyn.github.io/EFDesigner/ +// License (MIT): https://github.com/msawczyn/EFDesigner/blob/master/LICENSE +// +//------------------------------------------------------------------------------ + +using System; +using System.Collections.Generic; +using System.Linq; +using System.ComponentModel.DataAnnotations.Schema; +using System.Data.Entity; +using System.Data.Entity.Infrastructure.Annotations; + +namespace EF6_Ex2 +{ + /// + public partial class ModelOne2One : DbContext + { + #region DbSets + public virtual System.Data.Entity.DbSet Adresses { get; set; } + public virtual System.Data.Entity.DbSet People { get; set; } + #endregion DbSets + + #region Constructors + + partial void CustomInit(); + + /// + /// Default connection string + /// + public static string ConnectionString { get; set; } = @"Data Source=(localdb)\dbinstance;Initial Catalog=EFLocalDb;Integrated Security=True"; + /// + public ModelOne2One() : base(ConnectionString) + { + Configuration.LazyLoadingEnabled = true; + Configuration.ProxyCreationEnabled = true; + System.Data.Entity.Database.SetInitializer(new ModelOne2OneDatabaseInitializer()); + CustomInit(); + } + + /// + public ModelOne2One(string connectionString) : base(connectionString) + { + Configuration.LazyLoadingEnabled = true; + Configuration.ProxyCreationEnabled = true; + System.Data.Entity.Database.SetInitializer(new ModelOne2OneDatabaseInitializer()); + CustomInit(); + } + + /// + public ModelOne2One(string connectionString, System.Data.Entity.Infrastructure.DbCompiledModel model) : base(connectionString, model) + { + Configuration.LazyLoadingEnabled = true; + Configuration.ProxyCreationEnabled = true; + System.Data.Entity.Database.SetInitializer(new ModelOne2OneDatabaseInitializer()); + CustomInit(); + } + + /// + public ModelOne2One(System.Data.Common.DbConnection existingConnection, bool contextOwnsConnection) : base(existingConnection, contextOwnsConnection) + { + Configuration.LazyLoadingEnabled = true; + Configuration.ProxyCreationEnabled = true; + System.Data.Entity.Database.SetInitializer(new ModelOne2OneDatabaseInitializer()); + CustomInit(); + } + + /// + public ModelOne2One(System.Data.Common.DbConnection existingConnection, System.Data.Entity.Infrastructure.DbCompiledModel model, bool contextOwnsConnection) : base(existingConnection, model, contextOwnsConnection) + { + Configuration.LazyLoadingEnabled = true; + Configuration.ProxyCreationEnabled = true; + System.Data.Entity.Database.SetInitializer(new ModelOne2OneDatabaseInitializer()); + CustomInit(); + } + + /// + public ModelOne2One(System.Data.Entity.Infrastructure.DbCompiledModel model) : base(model) + { + Configuration.LazyLoadingEnabled = true; + Configuration.ProxyCreationEnabled = true; + System.Data.Entity.Database.SetInitializer(new ModelOne2OneDatabaseInitializer()); + CustomInit(); + } + + /// + public ModelOne2One(System.Data.Entity.Core.Objects.ObjectContext objectContext, bool dbContextOwnsObjectContext) : base(objectContext, dbContextOwnsObjectContext) + { + Configuration.LazyLoadingEnabled = true; + Configuration.ProxyCreationEnabled = true; + System.Data.Entity.Database.SetInitializer(new ModelOne2OneDatabaseInitializer()); + CustomInit(); + } + + #endregion Constructors + + partial void OnModelCreatingImpl(System.Data.Entity.DbModelBuilder modelBuilder); + partial void OnModelCreatedImpl(System.Data.Entity.DbModelBuilder modelBuilder); + + /// + protected override void OnModelCreating(System.Data.Entity.DbModelBuilder modelBuilder) + { + base.OnModelCreating(modelBuilder); + OnModelCreatingImpl(modelBuilder); + + modelBuilder.HasDefaultSchema("dbo"); + + modelBuilder.Entity() + .ToTable("Adresses") + .HasKey(t => t.Id); + modelBuilder.Entity() + .Property(t => t.Id) + .IsRequired() + .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity); + modelBuilder.Entity() + .Property(t => t.Timestamp) + .IsRequired() + .IsRowVersion(); + modelBuilder.Entity() + .HasRequired(x => x.Person) + .WithMany(x => x.Entity1) + .Map(x => x.MapKey("PersonId")); + + modelBuilder.Entity() + .ToTable("People") + .HasKey(t => t.Id); + modelBuilder.Entity() + .Property(t => t.Id) + .IsRequired() + .HasDatabaseGeneratedOption(DatabaseGeneratedOption.None); + modelBuilder.Entity() + .Property(t => t.FirstName) + .HasMaxLength(35); + modelBuilder.Entity() + .Property(t => t.MiddleName) + .HasMaxLength(35); + modelBuilder.Entity() + .Property(t => t.LastName) + .HasMaxLength(35); + modelBuilder.Entity() + .Property(t => t.PreferredName) + .HasMaxLength(75); + modelBuilder.Entity() + .Property(t => t.Email) + .HasMaxLength(45); + modelBuilder.Entity() + .Property(t => t.Phone) + .HasMaxLength(15); + + OnModelCreatedImpl(modelBuilder); + } + } +} diff --git a/src/Examples/EF6/Ex2_ModelOne2One/Generated_Ex2_ModelOne2One/ModelOne2OneDatabaseInitializer.generated.cs b/src/Examples/EF6/Ex2_ModelOne2One/Generated_Ex2_ModelOne2One/ModelOne2OneDatabaseInitializer.generated.cs new file mode 100644 index 000000000..99e706de7 --- /dev/null +++ b/src/Examples/EF6/Ex2_ModelOne2One/Generated_Ex2_ModelOne2One/ModelOne2OneDatabaseInitializer.generated.cs @@ -0,0 +1,24 @@ +//------------------------------------------------------------------------------ +// +// This code was generated from a template. +// +// Manual changes to this file may cause unexpected behavior in your application. +// Manual changes to this file will be overwritten if the code is regenerated. +// +// Produced by Entity Framework Visual Editor v3.0.7.2 +// Source: https://github.com/msawczyn/EFDesigner +// Visual Studio Marketplace: https://marketplace.visualstudio.com/items?itemName=michaelsawczyn.EFDesigner +// Documentation: https://msawczyn.github.io/EFDesigner/ +// License (MIT): https://github.com/msawczyn/EFDesigner/blob/master/LICENSE +// +//------------------------------------------------------------------------------ + +using System.Data.Entity; + +namespace EF6_Ex2 +{ + /// + public partial class ModelOne2OneDatabaseInitializer : CreateDatabaseIfNotExists + { + } +} diff --git a/src/Examples/EF6/Ex2_ModelOne2One/Generated_Ex2_ModelOne2One/ModelOne2OneDbMigrationConfiguration.generated.cs b/src/Examples/EF6/Ex2_ModelOne2One/Generated_Ex2_ModelOne2One/ModelOne2OneDbMigrationConfiguration.generated.cs new file mode 100644 index 000000000..0105e2429 --- /dev/null +++ b/src/Examples/EF6/Ex2_ModelOne2One/Generated_Ex2_ModelOne2One/ModelOne2OneDbMigrationConfiguration.generated.cs @@ -0,0 +1,33 @@ +//------------------------------------------------------------------------------ +// +// This code was generated from a template. +// +// Manual changes to this file may cause unexpected behavior in your application. +// Manual changes to this file will be overwritten if the code is regenerated. +// +// Produced by Entity Framework Visual Editor v3.0.7.2 +// Source: https://github.com/msawczyn/EFDesigner +// Visual Studio Marketplace: https://marketplace.visualstudio.com/items?itemName=michaelsawczyn.EFDesigner +// Documentation: https://msawczyn.github.io/EFDesigner/ +// License (MIT): https://github.com/msawczyn/EFDesigner/blob/master/LICENSE +// +//------------------------------------------------------------------------------ + +using System.Data.Entity.Migrations; + +namespace Migrations +{ + /// + public sealed partial class ModelOne2OneDbMigrationConfiguration : DbMigrationsConfiguration + { + partial void Init(); + + /// + public ModelOne2OneDbMigrationConfiguration() + { + AutomaticMigrationsEnabled = true; + AutomaticMigrationDataLossAllowed = false; + Init(); + } + } +} diff --git a/src/Examples/EF6/Ex2_ModelOne2One/Generated_Ex2_ModelOne2One/Person.generated.cs b/src/Examples/EF6/Ex2_ModelOne2One/Generated_Ex2_ModelOne2One/Person.generated.cs new file mode 100644 index 000000000..0352d53e2 --- /dev/null +++ b/src/Examples/EF6/Ex2_ModelOne2One/Generated_Ex2_ModelOne2One/Person.generated.cs @@ -0,0 +1,110 @@ +//------------------------------------------------------------------------------ +// +// This code was generated from a template. +// +// Manual changes to this file may cause unexpected behavior in your application. +// Manual changes to this file will be overwritten if the code is regenerated. +// +// Produced by Entity Framework Visual Editor v3.0.7.2 +// Source: https://github.com/msawczyn/EFDesigner +// Visual Studio Marketplace: https://marketplace.visualstudio.com/items?itemName=michaelsawczyn.EFDesigner +// Documentation: https://msawczyn.github.io/EFDesigner/ +// License (MIT): https://github.com/msawczyn/EFDesigner/blob/master/LICENSE +// +//------------------------------------------------------------------------------ + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using System.Linq; +using System.Runtime.CompilerServices; + +namespace EF6_Ex2 +{ + public partial class Person + { + partial void Init(); + + /// + /// Default constructor + /// + public Person() + { + Entity1 = new System.Collections.Generic.HashSet(); + + Init(); + } + + /************************************************************************* + * Properties + *************************************************************************/ + + /// + /// Identity, Required + /// + [Key] + [Required] + public long Id { get; set; } + + /// + /// Max length = 35 + /// + [MaxLength(35)] + [StringLength(35)] + public string FirstName { get; set; } + + /// + /// Max length = 35 + /// + [MaxLength(35)] + [StringLength(35)] + public string MiddleName { get; set; } + + /// + /// Max length = 35 + /// + [MaxLength(35)] + [StringLength(35)] + public string LastName { get; set; } + + /// + /// Max length = 75 + /// + [MaxLength(75)] + [StringLength(75)] + public string PreferredName { get; set; } + + public DateTime? DOB { get; set; } + + /// + /// Max length = 45 + /// + [MaxLength(45)] + [StringLength(45)] + public string Email { get; set; } + + /// + /// Max length = 15 + /// + [MaxLength(15)] + [StringLength(15)] + public string Phone { get; set; } + + /// + /// Concurrency token + /// + [Timestamp] + public Byte[] Timestamp { get; set; } + + /************************************************************************* + * Navigation properties + *************************************************************************/ + + public virtual ICollection Entity1 { get; private set; } + + } +} + diff --git a/src/Examples/EF6/Ex2_ModelOne2One/Generated_ModelOne2One/Address.generated.cs b/src/Examples/EF6/Ex2_ModelOne2One/Generated_ModelOne2One/Address.generated.cs new file mode 100644 index 000000000..31cacb72a --- /dev/null +++ b/src/Examples/EF6/Ex2_ModelOne2One/Generated_ModelOne2One/Address.generated.cs @@ -0,0 +1,115 @@ +//------------------------------------------------------------------------------ +// +// This code was generated from a template. +// +// Manual changes to this file may cause unexpected behavior in your application. +// Manual changes to this file will be overwritten if the code is regenerated. +// +// Produced by Entity Framework Visual Editor v3.0.7.2 +// Source: https://github.com/msawczyn/EFDesigner +// Visual Studio Marketplace: https://marketplace.visualstudio.com/items?itemName=michaelsawczyn.EFDesigner +// Documentation: https://msawczyn.github.io/EFDesigner/ +// License (MIT): https://github.com/msawczyn/EFDesigner/blob/master/LICENSE +// +//------------------------------------------------------------------------------ + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using System.Linq; +using System.Runtime.CompilerServices; + +namespace Ex2_ModelOne2One +{ + public partial class Address + { + partial void Init(); + + /// + /// Default constructor + /// + public Address() + { + Init(); + } + + /// + /// Public constructor with required data + /// + /// + /// + public Address(long addressid, global::Ex2_ModelOne2One.Person person) + { + this.AddressId = addressid; + + if (person == null) throw new ArgumentNullException(nameof(person)); + this.Person = person; + person.Address = this; + + Init(); + } + + /// + /// Static create function (for use in LINQ queries, etc.) + /// + /// + /// + public static Address Create(long addressid, global::Ex2_ModelOne2One.Person person) + { + return new Address(addressid, person); + } + + /************************************************************************* + * Properties + *************************************************************************/ + + /// + /// Identity, Required + /// + [Key] + [Required] + public long Id { get; set; } + + /// + /// Indexed, Required + /// + [Required] + public long AddressId { get; set; } + + public string Unit { get; set; } + + public string Number { get; set; } + + public string StreetLine1 { get; set; } + + public string StreetType { get; set; } + + public string StreetLine2 { get; set; } + + public string City { get; set; } + + public string PostalCode { get; set; } + + public string State { get; set; } + + public string Country { get; set; } + + public double? Latitude { get; set; } + + public double? Longitude { get; set; } + + /************************************************************************* + * Navigation properties + *************************************************************************/ + + /// + /// Required + /// + public virtual global::Ex2_ModelOne2One.Person Person { get; set; } + + } +} + diff --git a/src/Examples/EF6/Ex2_ModelOne2One/Generated_ModelOne2One/EFModelOne2One.generated.cs b/src/Examples/EF6/Ex2_ModelOne2One/Generated_ModelOne2One/EFModelOne2One.generated.cs new file mode 100644 index 000000000..f5a9d4278 --- /dev/null +++ b/src/Examples/EF6/Ex2_ModelOne2One/Generated_ModelOne2One/EFModelOne2One.generated.cs @@ -0,0 +1,164 @@ +//------------------------------------------------------------------------------ +// +// This code was generated from a template. +// +// Manual changes to this file may cause unexpected behavior in your application. +// Manual changes to this file will be overwritten if the code is regenerated. +// +// Produced by Entity Framework Visual Editor v3.0.7.2 +// Source: https://github.com/msawczyn/EFDesigner +// Visual Studio Marketplace: https://marketplace.visualstudio.com/items?itemName=michaelsawczyn.EFDesigner +// Documentation: https://msawczyn.github.io/EFDesigner/ +// License (MIT): https://github.com/msawczyn/EFDesigner/blob/master/LICENSE +// +//------------------------------------------------------------------------------ + +using System; +using System.Collections.Generic; +using System.Linq; +using System.ComponentModel.DataAnnotations.Schema; +using System.Data.Entity; +using System.Data.Entity.Infrastructure.Annotations; + +namespace Ex2_ModelOne2One +{ + /// + public partial class EFModelOne2One : DbContext + { + #region DbSets + public virtual System.Data.Entity.DbSet Address { get; set; } + public virtual System.Data.Entity.DbSet People { get; set; } + #endregion DbSets + + #region Constructors + + partial void CustomInit(); + + /// + /// Default connection string + /// + public static string ConnectionString { get; set; } = @"Data Source=(localdb)\dbinstance;Initial Catalog=EFLocalDb;Integrated Security=True"; + /// + public EFModelOne2One() : base(ConnectionString) + { + Configuration.LazyLoadingEnabled = true; + Configuration.ProxyCreationEnabled = true; + System.Data.Entity.Database.SetInitializer(new EFModelOne2OneDatabaseInitializer()); + CustomInit(); + } + + /// + public EFModelOne2One(string connectionString) : base(connectionString) + { + Configuration.LazyLoadingEnabled = true; + Configuration.ProxyCreationEnabled = true; + System.Data.Entity.Database.SetInitializer(new EFModelOne2OneDatabaseInitializer()); + CustomInit(); + } + + /// + public EFModelOne2One(string connectionString, System.Data.Entity.Infrastructure.DbCompiledModel model) : base(connectionString, model) + { + Configuration.LazyLoadingEnabled = true; + Configuration.ProxyCreationEnabled = true; + System.Data.Entity.Database.SetInitializer(new EFModelOne2OneDatabaseInitializer()); + CustomInit(); + } + + /// + public EFModelOne2One(System.Data.Common.DbConnection existingConnection, bool contextOwnsConnection) : base(existingConnection, contextOwnsConnection) + { + Configuration.LazyLoadingEnabled = true; + Configuration.ProxyCreationEnabled = true; + System.Data.Entity.Database.SetInitializer(new EFModelOne2OneDatabaseInitializer()); + CustomInit(); + } + + /// + public EFModelOne2One(System.Data.Common.DbConnection existingConnection, System.Data.Entity.Infrastructure.DbCompiledModel model, bool contextOwnsConnection) : base(existingConnection, model, contextOwnsConnection) + { + Configuration.LazyLoadingEnabled = true; + Configuration.ProxyCreationEnabled = true; + System.Data.Entity.Database.SetInitializer(new EFModelOne2OneDatabaseInitializer()); + CustomInit(); + } + + /// + public EFModelOne2One(System.Data.Entity.Infrastructure.DbCompiledModel model) : base(model) + { + Configuration.LazyLoadingEnabled = true; + Configuration.ProxyCreationEnabled = true; + System.Data.Entity.Database.SetInitializer(new EFModelOne2OneDatabaseInitializer()); + CustomInit(); + } + + /// + public EFModelOne2One(System.Data.Entity.Core.Objects.ObjectContext objectContext, bool dbContextOwnsObjectContext) : base(objectContext, dbContextOwnsObjectContext) + { + Configuration.LazyLoadingEnabled = true; + Configuration.ProxyCreationEnabled = true; + System.Data.Entity.Database.SetInitializer(new EFModelOne2OneDatabaseInitializer()); + CustomInit(); + } + + #endregion Constructors + + partial void OnModelCreatingImpl(System.Data.Entity.DbModelBuilder modelBuilder); + partial void OnModelCreatedImpl(System.Data.Entity.DbModelBuilder modelBuilder); + + /// + protected override void OnModelCreating(System.Data.Entity.DbModelBuilder modelBuilder) + { + base.OnModelCreating(modelBuilder); + OnModelCreatingImpl(modelBuilder); + + modelBuilder.HasDefaultSchema("dbo"); + + modelBuilder.Entity() + .ToTable("Address") + .HasKey(t => t.Id); + modelBuilder.Entity() + .Property(t => t.Id) + .IsRequired() + .HasDatabaseGeneratedOption(DatabaseGeneratedOption.None); + modelBuilder.Entity() + .Property(t => t.AddressId) + .IsRequired() + .HasColumnAnnotation("Index", new IndexAnnotation(new IndexAttribute())); + modelBuilder.Entity().HasIndex(t => t.AddressId) + .IsUnique(); + modelBuilder.Entity() + .HasRequired(x => x.Person) + .WithOptional(x => x.Address) + .WillCascadeOnDelete(false); + + modelBuilder.Entity() + .ToTable("People") + .HasKey(t => t.PersonId); + modelBuilder.Entity() + .Property(t => t.PersonId) + .IsRequired() + .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity); + modelBuilder.Entity() + .Property(t => t.FirstName) + .HasMaxLength(35); + modelBuilder.Entity() + .Property(t => t.MiddleName) + .HasMaxLength(35); + modelBuilder.Entity() + .Property(t => t.LastName) + .HasMaxLength(35); + modelBuilder.Entity() + .Property(t => t.PreferredName) + .HasMaxLength(75); + modelBuilder.Entity() + .Property(t => t.Email) + .HasMaxLength(45); + modelBuilder.Entity() + .Property(t => t.Phone) + .HasMaxLength(15); + + OnModelCreatedImpl(modelBuilder); + } + } +} diff --git a/src/Examples/EF6/Ex2_ModelOne2One/Generated_ModelOne2One/EFModelOne2OneDatabaseInitializer.generated.cs b/src/Examples/EF6/Ex2_ModelOne2One/Generated_ModelOne2One/EFModelOne2OneDatabaseInitializer.generated.cs new file mode 100644 index 000000000..b883a2259 --- /dev/null +++ b/src/Examples/EF6/Ex2_ModelOne2One/Generated_ModelOne2One/EFModelOne2OneDatabaseInitializer.generated.cs @@ -0,0 +1,24 @@ +//------------------------------------------------------------------------------ +// +// This code was generated from a template. +// +// Manual changes to this file may cause unexpected behavior in your application. +// Manual changes to this file will be overwritten if the code is regenerated. +// +// Produced by Entity Framework Visual Editor v3.0.7.2 +// Source: https://github.com/msawczyn/EFDesigner +// Visual Studio Marketplace: https://marketplace.visualstudio.com/items?itemName=michaelsawczyn.EFDesigner +// Documentation: https://msawczyn.github.io/EFDesigner/ +// License (MIT): https://github.com/msawczyn/EFDesigner/blob/master/LICENSE +// +//------------------------------------------------------------------------------ + +using System.Data.Entity; + +namespace Ex2_ModelOne2One +{ + /// + public partial class EFModelOne2OneDatabaseInitializer : MigrateDatabaseToLatestVersion + { + } +} diff --git a/src/Examples/EF6/Ex2_ModelOne2One/Generated_ModelOne2One/EFModelOne2OneDbMigrationConfiguration.generated.cs b/src/Examples/EF6/Ex2_ModelOne2One/Generated_ModelOne2One/EFModelOne2OneDbMigrationConfiguration.generated.cs new file mode 100644 index 000000000..28531ddaf --- /dev/null +++ b/src/Examples/EF6/Ex2_ModelOne2One/Generated_ModelOne2One/EFModelOne2OneDbMigrationConfiguration.generated.cs @@ -0,0 +1,33 @@ +//------------------------------------------------------------------------------ +// +// This code was generated from a template. +// +// Manual changes to this file may cause unexpected behavior in your application. +// Manual changes to this file will be overwritten if the code is regenerated. +// +// Produced by Entity Framework Visual Editor v3.0.7.2 +// Source: https://github.com/msawczyn/EFDesigner +// Visual Studio Marketplace: https://marketplace.visualstudio.com/items?itemName=michaelsawczyn.EFDesigner +// Documentation: https://msawczyn.github.io/EFDesigner/ +// License (MIT): https://github.com/msawczyn/EFDesigner/blob/master/LICENSE +// +//------------------------------------------------------------------------------ + +using System.Data.Entity.Migrations; + +namespace Migrations +{ + /// + public sealed partial class EFModelOne2OneDbMigrationConfiguration : DbMigrationsConfiguration + { + partial void Init(); + + /// + public EFModelOne2OneDbMigrationConfiguration() + { + AutomaticMigrationsEnabled = true; + AutomaticMigrationDataLossAllowed = false; + Init(); + } + } +} diff --git a/src/Examples/EF6/Ex2_ModelOne2One/Generated_ModelOne2One/Person.generated.cs b/src/Examples/EF6/Ex2_ModelOne2One/Generated_ModelOne2One/Person.generated.cs new file mode 100644 index 000000000..557b53f8a --- /dev/null +++ b/src/Examples/EF6/Ex2_ModelOne2One/Generated_ModelOne2One/Person.generated.cs @@ -0,0 +1,102 @@ +//------------------------------------------------------------------------------ +// +// This code was generated from a template. +// +// Manual changes to this file may cause unexpected behavior in your application. +// Manual changes to this file will be overwritten if the code is regenerated. +// +// Produced by Entity Framework Visual Editor v3.0.7.2 +// Source: https://github.com/msawczyn/EFDesigner +// Visual Studio Marketplace: https://marketplace.visualstudio.com/items?itemName=michaelsawczyn.EFDesigner +// Documentation: https://msawczyn.github.io/EFDesigner/ +// License (MIT): https://github.com/msawczyn/EFDesigner/blob/master/LICENSE +// +//------------------------------------------------------------------------------ + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using System.Linq; +using System.Runtime.CompilerServices; + +namespace Ex2_ModelOne2One +{ + public partial class Person + { + partial void Init(); + + /// + /// Default constructor + /// + public Person() + { + Init(); + } + + /************************************************************************* + * Properties + *************************************************************************/ + + /// + /// Identity, Indexed, Required + /// + [Key] + [Required] + public long PersonId { get; set; } + + /// + /// Max length = 35 + /// + [MaxLength(35)] + [StringLength(35)] + public string FirstName { get; set; } + + /// + /// Max length = 35 + /// + [MaxLength(35)] + [StringLength(35)] + public string MiddleName { get; set; } + + /// + /// Max length = 35 + /// + [MaxLength(35)] + [StringLength(35)] + public string LastName { get; set; } + + /// + /// Max length = 75 + /// + [MaxLength(75)] + [StringLength(75)] + public string PreferredName { get; set; } + + public DateTime? DOB { get; set; } + + /// + /// Max length = 45 + /// + [MaxLength(45)] + [StringLength(45)] + public string Email { get; set; } + + /// + /// Max length = 15 + /// + [MaxLength(15)] + [StringLength(15)] + public string Phone { get; set; } + + /************************************************************************* + * Navigation properties + *************************************************************************/ + + public virtual global::Ex2_ModelOne2One.Address Address { get; set; } + + } +} + diff --git a/src/Examples/EF6/Ex2_ModelOne2One/Program.cs b/src/Examples/EF6/Ex2_ModelOne2One/Program.cs new file mode 100644 index 000000000..2625d68ac --- /dev/null +++ b/src/Examples/EF6/Ex2_ModelOne2One/Program.cs @@ -0,0 +1,141 @@ +using System; +using System.Collections.Generic; +using System.Data.SqlClient; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace Ex2_ModelOne2One +{ + static class Program + { + /// + /// The main entry point for the application. + /// + [STAThread] + static void Main() + { + Application.EnableVisualStyles(); + Application.SetCompatibleTextRenderingDefault(false); + + SetupLocalDb("mssqllocaldb", "EFVisualExamples"); + + Application.Run(new FrmOne2One()); + + } + + + + static void SetupLocalDb(string InstanceName = "mssqllocaldb", string DatabaseName = "EFVisualExamples") //This is a default instance name in local DB v13 + { + //Step 1: Islocaldb installed? + if (!CreateLocalDBInstance(InstanceName)) + { + + MessageBox.Show("CRITICAL ERROR: SqlLocalDb software is not installed!"); + + //Download SQL Server Express - LocalDB + // https://www.sqlshack.com/install-microsoft-sql-server-express-localdb/ + // https://www.microsoft.com/en-au/download/confirmation.aspx?id=101064 + // Microsoft SQL Server Express LocalDB supports silent installation. A user should download SqlLocalDB.msi and run the Command Prompt window as an administrator. Then, they should paste the following command: + // msiexec /i SqlLocalDB.msi /qn IACCEPTSQLLOCALDBLICENSETERMS = YES + string url = @"https://www.microsoft.com/en-au/download/confirmation.aspx?id=101064"; + Process.Start(url); + + Application.Exit(); + } + + //Step2: Create Database + + string connectionString = @"Data Source=(localdb)\" + InstanceName + $"; Integrated Security=True;"; + + if (!CheckDatabaseExists(connectionString, DatabaseName)) + { + //This is fixed -canot be changed + string UserPath = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); + + SqlConnection connection = new SqlConnection(connectionString); + using (connection) + { + connection.Open(); + + string sql = $@" + CREATE DATABASE + {DatabaseName} + ON PRIMARY ( + NAME={DatabaseName}_data, + FILENAME = '{UserPath}\{DatabaseName}.mdf' + ) + LOG ON ( + NAME={DatabaseName}_log, + FILENAME = '{UserPath}\{DatabaseName}.ldf' + )"; + + SqlCommand command = new SqlCommand(sql, connection); + try + { + command.ExecuteNonQuery(); + } + catch (Exception ex) + { + MessageBox.Show($"CRITICAL ERROR: Database cannot be created\r\n{ex.ToString()}\r\nDoes Db exists in another instance?\r\n(Note: You cannot duplicate names across instances- requires unique name)"); + //You can debug using commandline + //>sqllocaldb info mssqllocaldb + + //https://docs.microsoft.com/en-us/sql/tools/sqllocaldb-utility?view=sql-server-ver15 + + string url = @"https://docs.microsoft.com/en-us/sql/relational-databases/express-localdb-instance-apis/command-line-management-tool-sqllocaldb-exe?view=sql-server-ver15"; + Process.Start(url); + + Application.Exit(); + } + + MessageBox.Show($" A New empty Local Database has been created successfully!\r\n\r\nSQLLOCALDB:{InstanceName}\r\nDATABASE:{DatabaseName}"); + } + } + } + + static bool CreateLocalDBInstance(string InstanceName) + { + // Lists all instances + // >sqllocaldb info + + // Start the child process. + Process p = new Process(); + // Redirect the output stream of the child process. + p.StartInfo.UseShellExecute = false; + p.StartInfo.RedirectStandardOutput = true; + p.StartInfo.FileName = "cmd.exe"; + p.StartInfo.Arguments = $"/C sqllocaldb c {InstanceName}"; //Create Local Db Instance + p.StartInfo.CreateNoWindow = true; + p.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; + p.Start(); + string sOutput = p.StandardOutput.ReadToEnd(); + p.WaitForExit(); + + //If LocalDb is not installed then it will return that 'sqllocaldb' is not recognized as an internal or external command operable program or batch file. + if (sOutput == null || sOutput.Trim().Length == 0 || sOutput.Contains("not recognized")) + return false; + if (sOutput.ToLower().Contains(InstanceName)) + return true; + return false; + } + + public static bool CheckDatabaseExists(string connectionString, string databaseName) + { + + using (var connection = new SqlConnection(connectionString)) + { + using (var command = new SqlCommand($"SELECT db_id('{databaseName}')", connection)) + { + connection.Open(); + var retval = command.ExecuteScalar(); + + return (retval != DBNull.Value); + } + } + } + } +} \ No newline at end of file diff --git a/src/Examples/EF6/Ex2_ModelOne2One/Properties/AssemblyInfo.cs b/src/Examples/EF6/Ex2_ModelOne2One/Properties/AssemblyInfo.cs new file mode 100644 index 000000000..3a69170f5 --- /dev/null +++ b/src/Examples/EF6/Ex2_ModelOne2One/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("Ex2_ModelOne2One")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("Ex2_ModelOne2One")] +[assembly: AssemblyCopyright("Copyright © 2021")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("357ab96c-3ea3-4f76-b416-b265661e8bb6")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/src/Examples/EF6/Ex2_ModelOne2One/Properties/Resources.Designer.cs b/src/Examples/EF6/Ex2_ModelOne2One/Properties/Resources.Designer.cs new file mode 100644 index 000000000..7507ca046 --- /dev/null +++ b/src/Examples/EF6/Ex2_ModelOne2One/Properties/Resources.Designer.cs @@ -0,0 +1,70 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + + +namespace Ex2_ModelOne2One.Properties +{ + /// + /// A strongly-typed resource class, for looking up localized strings, etc. + /// + // This class was auto-generated by the StronglyTypedResourceBuilder + // class via a tool like ResGen or Visual Studio. + // To add or remove a member, edit your .ResX file then rerun ResGen + // with the /str option, or rebuild your VS project. + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + internal class Resources + { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal Resources() + { + } + + /// + /// Returns the cached ResourceManager instance used by this class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Resources.ResourceManager ResourceManager + { + get + { + if ((resourceMan == null)) + { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Ex2_ModelOne2One.Properties.Resources", typeof(Resources).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// + /// Overrides the current thread's CurrentUICulture property for all + /// resource lookups using this strongly typed resource class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Globalization.CultureInfo Culture + { + get + { + return resourceCulture; + } + set + { + resourceCulture = value; + } + } + } +} diff --git a/src/Examples/EF6/Ex2_ModelOne2One/Properties/Resources.resx b/src/Examples/EF6/Ex2_ModelOne2One/Properties/Resources.resx new file mode 100644 index 000000000..af7dbebba --- /dev/null +++ b/src/Examples/EF6/Ex2_ModelOne2One/Properties/Resources.resx @@ -0,0 +1,117 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/src/Examples/EF6/Ex2_ModelOne2One/Properties/Settings.Designer.cs b/src/Examples/EF6/Ex2_ModelOne2One/Properties/Settings.Designer.cs new file mode 100644 index 000000000..a91063860 --- /dev/null +++ b/src/Examples/EF6/Ex2_ModelOne2One/Properties/Settings.Designer.cs @@ -0,0 +1,29 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + + +namespace Ex2_ModelOne2One.Properties +{ + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")] + internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase + { + + private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); + + public static Settings Default + { + get + { + return defaultInstance; + } + } + } +} diff --git a/src/Examples/EF6/Ex2_ModelOne2One/Properties/Settings.settings b/src/Examples/EF6/Ex2_ModelOne2One/Properties/Settings.settings new file mode 100644 index 000000000..39645652a --- /dev/null +++ b/src/Examples/EF6/Ex2_ModelOne2One/Properties/Settings.settings @@ -0,0 +1,7 @@ + + + + + + + diff --git a/src/Examples/EF6/Ex3_ModelManytoMany/App.config b/src/Examples/EF6/Ex3_ModelManytoMany/App.config new file mode 100644 index 000000000..0d61d3093 --- /dev/null +++ b/src/Examples/EF6/Ex3_ModelManytoMany/App.config @@ -0,0 +1,15 @@ + + + + +
+ + + + + + + + + + \ No newline at end of file diff --git a/src/Examples/EF6/Ex3_ModelManytoMany/EFModelOnetoMany.cs b/src/Examples/EF6/Ex3_ModelManytoMany/EFModelOnetoMany.cs new file mode 100644 index 000000000..6153a7d78 --- /dev/null +++ b/src/Examples/EF6/Ex3_ModelManytoMany/EFModelOnetoMany.cs @@ -0,0 +1 @@ + diff --git a/src/Examples/EF6/Ex3_ModelManytoMany/EFModelOnetoMany.efmodel b/src/Examples/EF6/Ex3_ModelManytoMany/EFModelOnetoMany.efmodel new file mode 100644 index 000000000..58c7ac1c8 --- /dev/null +++ b/src/Examples/EF6/Ex3_ModelManytoMany/EFModelOnetoMany.efmodel @@ -0,0 +1,36 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/Examples/EF6/Ex3_ModelManytoMany/EFModelOnetoMany.efmodel.diagramx b/src/Examples/EF6/Ex3_ModelManytoMany/EFModelOnetoMany.efmodel.diagramx new file mode 100644 index 000000000..187b9d670 --- /dev/null +++ b/src/Examples/EF6/Ex3_ModelManytoMany/EFModelOnetoMany.efmodel.diagramx @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/Examples/EF6/Ex3_ModelManytoMany/EFModelOnetoMany.tt b/src/Examples/EF6/Ex3_ModelManytoMany/EFModelOnetoMany.tt new file mode 100644 index 000000000..fd8799bb2 --- /dev/null +++ b/src/Examples/EF6/Ex3_ModelManytoMany/EFModelOnetoMany.tt @@ -0,0 +1,74 @@ +<#@ template inherits="Microsoft.VisualStudio.TextTemplating.VSHost.ModelingTextTransformation" debug="true" + hostSpecific="true" language="C#" compilerOptions="/langversion:latest"#> +<#@ CleanupBehavior processor="T4VSHost" CleanupAfterProcessingtemplate="true" #> +<#@ assembly name="System.Data.Entity.Design.dll" +#><#@ assembly name="EnvDTE" +#><#@ include file="EFDesigner.ttinclude" once="true" +#><#@ output extension=".cs" +#><#@ import namespace="System.Linq" +#><#@ import namespace="System" +#><#@ import namespace="System.Data.Entity.Design.PluralizationServices" +#><#@ import namespace="System.Globalization" +#><#@ import namespace="Sawczyn.EFDesigner.EFModel" +#><#@ EFModel processor="EFModelDirectiveProcessor" requires="FileName='EFModelOnetoMany.efmodel'" +#><# + Manager manager = Manager.Create(Host, GenerationEnvironment); + manager.FileNameMarker = ModelRoot.FileNameMarker; + + if (ModelRoot.Classes.Any()) + { + manager.StartHeader(false); + Output("//------------------------------------------------------------------------------"); + Output("// "); + Output("// This code was generated from a template."); + Output("//"); + Output("// Manual changes to this file may cause unexpected behavior in your application."); + Output("// Manual changes to this file will be overwritten if the code is regenerated."); + Output("//"); + Output("// Produced by Entity Framework Visual Editor v" + ModelRoot.DSLVersion); + Output("// Source: https://github.com/msawczyn/EFDesigner"); + Output("// Visual Studio Marketplace: https://marketplace.visualstudio.com/items?itemName=michaelsawczyn.EFDesigner"); + Output("// Documentation: https://msawczyn.github.io/EFDesigner/"); + Output("// License (MIT): https://github.com/msawczyn/EFDesigner/blob/master/LICENSE"); + Output("// "); + Output("//------------------------------------------------------------------------------"); + NL(); + + EFModelGenerator generator; + + switch (ModelRoot.EntityFrameworkVersion) + { + case EFVersion.EF6: + { + generator = new EF6ModelGenerator(this); + break; + } + + case EFVersion.EFCore: + { + switch ((int)ModelRoot.GetEntityFrameworkPackageVersionNum()) + { + case 2: + generator = new EFCore2ModelGenerator(this); + break; + + case 3: + generator = new EFCore3ModelGenerator(this); + break; + + default: + generator = new EFCore5ModelGenerator(this); + break; + } + break; + } + + default: + throw new InvalidOperationException("Unsupported Entity Framework version"); + } + + generator.Generate(manager); + } + + manager.Process(true); +#> \ No newline at end of file diff --git a/src/Examples/EF6/Ex3_ModelManytoMany/Ex3_ModelOnetoMany.csproj b/src/Examples/EF6/Ex3_ModelManytoMany/Ex3_ModelOnetoMany.csproj new file mode 100644 index 000000000..2676763c9 --- /dev/null +++ b/src/Examples/EF6/Ex3_ModelManytoMany/Ex3_ModelOnetoMany.csproj @@ -0,0 +1,117 @@ + + + + + Debug + AnyCPU + {CD767834-7004-444D-B7D8-58AC359ED441} + WinExe + Ex3_ModelManytoMany + Ex3_ModelManytoMany + v4.8 + 512 + true + true + + + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + Ex3_ModelManytoMany.Program + + + + + + + + + + + + + + + + + + True + True + EFModelOnetoMany.tt + + + Form + + + FrmModelOnetoMany.cs + + + + + + + + + + FrmModelOnetoMany.cs + + + ResXFileCodeGenerator + Resources.Designer.cs + Designer + + + True + Resources.resx + + + + EFModelOnetoMany.efmodel + + + SettingsSingleFileGenerator + Settings.Designer.cs + + + True + Settings.settings + True + + + + + + + + + + + 6.4.4 + + + + + TextTemplatingFileGenerator + EFModelOnetoMany.cs + + + + \ No newline at end of file diff --git a/src/Examples/EF6/Ex3_ModelManytoMany/FrmModelOnetoMany.Designer.cs b/src/Examples/EF6/Ex3_ModelManytoMany/FrmModelOnetoMany.Designer.cs new file mode 100644 index 000000000..be8708669 --- /dev/null +++ b/src/Examples/EF6/Ex3_ModelManytoMany/FrmModelOnetoMany.Designer.cs @@ -0,0 +1,101 @@ + +namespace Ex3_ModelManytoMany +{ + partial class FrmModelOnetoMany + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + this.txtDebug = new System.Windows.Forms.TextBox(); + this.label1 = new System.Windows.Forms.Label(); + this.txtConnection = new System.Windows.Forms.TextBox(); + this.btnTestOne2One = new System.Windows.Forms.Button(); + this.SuspendLayout(); + // + // txtDebug + // + this.txtDebug.Location = new System.Drawing.Point(211, 135); + this.txtDebug.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + this.txtDebug.Multiline = true; + this.txtDebug.Name = "txtDebug"; + this.txtDebug.Size = new System.Drawing.Size(710, 266); + this.txtDebug.TabIndex = 12; + // + // label1 + // + this.label1.AutoSize = true; + this.label1.Location = new System.Drawing.Point(207, 49); + this.label1.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); + this.label1.Name = "label1"; + this.label1.Size = new System.Drawing.Size(167, 20); + this.label1.TabIndex = 11; + this.label1.Text = "Sql Server Connection"; + // + // txtConnection + // + this.txtConnection.Location = new System.Drawing.Point(211, 74); + this.txtConnection.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + this.txtConnection.Name = "txtConnection"; + this.txtConnection.Size = new System.Drawing.Size(710, 26); + this.txtConnection.TabIndex = 10; + this.txtConnection.Text = "..."; + // + // btnTestOne2One + // + this.btnTestOne2One.Location = new System.Drawing.Point(33, 135); + this.btnTestOne2One.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + this.btnTestOne2One.Name = "btnTestOne2One"; + this.btnTestOne2One.Size = new System.Drawing.Size(170, 63); + this.btnTestOne2One.TabIndex = 9; + this.btnTestOne2One.Text = "Test One to Many"; + this.btnTestOne2One.UseVisualStyleBackColor = true; + this.btnTestOne2One.Click += new System.EventHandler(this.btnMany2Many_Click); + // + // FrmModelOnetoMany + // + this.AutoScaleDimensions = new System.Drawing.SizeF(9F, 20F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(958, 450); + this.Controls.Add(this.txtDebug); + this.Controls.Add(this.label1); + this.Controls.Add(this.txtConnection); + this.Controls.Add(this.btnTestOne2One); + this.Name = "FrmModelOnetoMany"; + this.Text = "Ex 3: One 2 Many - Authors & Books"; + this.Load += new System.EventHandler(this.FrmMany2Many_Load); + this.ResumeLayout(false); + this.PerformLayout(); + + } + + #endregion + + private System.Windows.Forms.TextBox txtDebug; + private System.Windows.Forms.Label label1; + private System.Windows.Forms.TextBox txtConnection; + private System.Windows.Forms.Button btnTestOne2One; + } +} \ No newline at end of file diff --git a/src/Examples/EF6/Ex3_ModelManytoMany/FrmModelOnetoMany.cs b/src/Examples/EF6/Ex3_ModelManytoMany/FrmModelOnetoMany.cs new file mode 100644 index 000000000..835534008 --- /dev/null +++ b/src/Examples/EF6/Ex3_ModelManytoMany/FrmModelOnetoMany.cs @@ -0,0 +1,121 @@ +using System; +using System.Collections.Generic; +using System.Data.Entity.Validation; +using System.Globalization; +using System.Windows.Forms; + +namespace Ex3_ModelManytoMany +{ + public partial class FrmModelOnetoMany : Form + { + public FrmModelOnetoMany() + { + InitializeComponent(); + } + + private void FrmMany2Many_Load(object sender, EventArgs e) + { + using (EFModelOnetoMany context = new EFModelOnetoMany()) + { + txtConnection.Text = context.Database.Connection.ConnectionString; + } + } + + private void btnMany2Many_Click(object sender, EventArgs e) + { + //https://entityframework.net/one-to-many-relationship + TestOne2Many(); + } + + void TestOne2Many() + { + txtDebug.Text = "TestMany2May()\r\n"; + + using (EFModelOnetoMany context = new EFModelOnetoMany()) + { + // Perform data access using the context + context.Database.Log = Console.Write; + + context.Database.Delete(); + txtDebug.Text += "Deleted DB\r\n"; + + context.Database.CreateIfNotExists(); + txtDebug.Text += "Created DB\r\n"; + + + txtDebug.Text += "\r\nEach Author can have many Books\r\n----------------\r\n"; + Author AuthorMT = new Author() + { + Firstname = "Mark", + Lastname = "Twain" + + }; + + + Author AuthorIA = new Author() + { + Firstname = "Izzac", + Lastname = "Azimov" + + }; + + + Book book = Book.Create(AuthorIA); + book.Title = "The Complete Robot"; + book.ISBN = "65445635"; + + + Book book1 = Book.Create(AuthorIA); + book.Title = "Youth"; + book.ISBN = "43252345243"; + + Book book2 = Book.Create(AuthorMT); + book2.Title = "The Adventures of Huckleberry Finn"; + book2.ISBN = "6436546345"; + + Book book3 = Book.Create(AuthorMT); + book3.Title = "The Prince and the Pauper"; + book3.ISBN = "34523452"; + + + context.Authors.Add(AuthorMT); + context.Authors.Add(AuthorIA); + + try + { + context.SaveChanges(); + } + catch (System.Data.Entity.Validation.DbEntityValidationException dbEx) + { + Exception raise = dbEx; + foreach (DbEntityValidationResult validationErrors in dbEx.EntityValidationErrors) + { + foreach (DbValidationError validationError in validationErrors.ValidationErrors) + { + string message = string.Format("{0}:{1}", + validationErrors.Entry.Entity.ToString(), + validationError.ErrorMessage); + // raise a new exception nesting the current instance as InnerException + raise = new InvalidOperationException(message, raise); + } + } + throw raise; + } + + //Read it back + var items = context.Authors; + + foreach (var x in items) + { + txtDebug.Text += "---------\r\n"; + foreach (Book books in x.Books) + { + txtDebug.Text += String.Format("Auth Id {0} - Author: {1} {2} & Book Title:{3} - {4}", x.AuthorId, x.Firstname, x.Lastname, book.Title, book.ISBN ) + "\r\n"; + } + + } + + } + } + } +} \ No newline at end of file diff --git a/src/Examples/EF6/Ex3_ModelManytoMany/FrmModelOnetoMany.resx b/src/Examples/EF6/Ex3_ModelManytoMany/FrmModelOnetoMany.resx new file mode 100644 index 000000000..1af7de150 --- /dev/null +++ b/src/Examples/EF6/Ex3_ModelManytoMany/FrmModelOnetoMany.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/src/Examples/EF6/Ex3_ModelManytoMany/Generated_One2Many/Author.generated.cs b/src/Examples/EF6/Ex3_ModelManytoMany/Generated_One2Many/Author.generated.cs new file mode 100644 index 000000000..b6b2f098d --- /dev/null +++ b/src/Examples/EF6/Ex3_ModelManytoMany/Generated_One2Many/Author.generated.cs @@ -0,0 +1,76 @@ +//------------------------------------------------------------------------------ +// +// This code was generated from a template. +// +// Manual changes to this file may cause unexpected behavior in your application. +// Manual changes to this file will be overwritten if the code is regenerated. +// +// Produced by Entity Framework Visual Editor v3.0.7.2 +// Source: https://github.com/msawczyn/EFDesigner +// Visual Studio Marketplace: https://marketplace.visualstudio.com/items?itemName=michaelsawczyn.EFDesigner +// Documentation: https://msawczyn.github.io/EFDesigner/ +// License (MIT): https://github.com/msawczyn/EFDesigner/blob/master/LICENSE +// +//------------------------------------------------------------------------------ + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using System.Linq; +using System.Runtime.CompilerServices; + +namespace Ex3_ModelManytoMany +{ + public partial class Author + { + partial void Init(); + + /// + /// Default constructor + /// + public Author() + { + Books = new System.Collections.Generic.HashSet(); + + Init(); + } + + /************************************************************************* + * Properties + *************************************************************************/ + + /// + /// Identity, Indexed, Required + /// Unique identifier + /// + [Key] + [Required] + [System.ComponentModel.Description("Unique identifier")] + public long AuthorId { get; set; } + + /// + /// Max length = 125 + /// + [MaxLength(125)] + [StringLength(125)] + public string Firstname { get; set; } + + /// + /// Max length = 125 + /// + [MaxLength(125)] + [StringLength(125)] + public string Lastname { get; set; } + + /************************************************************************* + * Navigation properties + *************************************************************************/ + + public virtual ICollection Books { get; private set; } + + } +} + diff --git a/src/Examples/EF6/Ex3_ModelManytoMany/Generated_One2Many/Book.generated.cs b/src/Examples/EF6/Ex3_ModelManytoMany/Generated_One2Many/Book.generated.cs new file mode 100644 index 000000000..d2eb35f1f --- /dev/null +++ b/src/Examples/EF6/Ex3_ModelManytoMany/Generated_One2Many/Book.generated.cs @@ -0,0 +1,101 @@ +//------------------------------------------------------------------------------ +// +// This code was generated from a template. +// +// Manual changes to this file may cause unexpected behavior in your application. +// Manual changes to this file will be overwritten if the code is regenerated. +// +// Produced by Entity Framework Visual Editor v3.0.7.2 +// Source: https://github.com/msawczyn/EFDesigner +// Visual Studio Marketplace: https://marketplace.visualstudio.com/items?itemName=michaelsawczyn.EFDesigner +// Documentation: https://msawczyn.github.io/EFDesigner/ +// License (MIT): https://github.com/msawczyn/EFDesigner/blob/master/LICENSE +// +//------------------------------------------------------------------------------ + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using System.Linq; +using System.Runtime.CompilerServices; + +namespace Ex3_ModelManytoMany +{ + public partial class Book + { + partial void Init(); + + /// + /// Default constructor. Protected due to required properties, but present because EF needs it. + /// + protected Book() + { + Init(); + } + + /// + /// Replaces default constructor, since it's protected. Caller assumes responsibility for setting all required values before saving. + /// + public static Book CreateBookUnsafe() + { + return new Book(); + } + + /// + /// Public constructor with required data + /// + /// + public Book(global::Ex3_ModelManytoMany.Author _author0) + { + if (_author0 == null) throw new ArgumentNullException(nameof(_author0)); + _author0.Books.Add(this); + + Init(); + } + + /// + /// Static create function (for use in LINQ queries, etc.) + /// + /// + public static Book Create(global::Ex3_ModelManytoMany.Author _author0) + { + return new Book(_author0); + } + + /************************************************************************* + * Properties + *************************************************************************/ + + /// + /// Identity, Indexed, Required + /// Unique identifier + /// + [Key] + [Required] + [System.ComponentModel.Description("Unique identifier")] + public long BookId { get; set; } + + /// + /// Max length = 255 + /// + [MaxLength(255)] + [StringLength(255)] + public string Title { get; set; } + + /// + /// Max length = 75 + /// + [MaxLength(75)] + [StringLength(75)] + public string ISBN { get; set; } + + /************************************************************************* + * Navigation properties + *************************************************************************/ + + } +} + diff --git a/src/Examples/EF6/Ex3_ModelManytoMany/Generated_One2Many/EFModelOnetoMany.generated.cs b/src/Examples/EF6/Ex3_ModelManytoMany/Generated_One2Many/EFModelOnetoMany.generated.cs new file mode 100644 index 000000000..ce3573ff4 --- /dev/null +++ b/src/Examples/EF6/Ex3_ModelManytoMany/Generated_One2Many/EFModelOnetoMany.generated.cs @@ -0,0 +1,152 @@ +//------------------------------------------------------------------------------ +// +// This code was generated from a template. +// +// Manual changes to this file may cause unexpected behavior in your application. +// Manual changes to this file will be overwritten if the code is regenerated. +// +// Produced by Entity Framework Visual Editor v3.0.7.2 +// Source: https://github.com/msawczyn/EFDesigner +// Visual Studio Marketplace: https://marketplace.visualstudio.com/items?itemName=michaelsawczyn.EFDesigner +// Documentation: https://msawczyn.github.io/EFDesigner/ +// License (MIT): https://github.com/msawczyn/EFDesigner/blob/master/LICENSE +// +//------------------------------------------------------------------------------ + +using System; +using System.Collections.Generic; +using System.Linq; +using System.ComponentModel.DataAnnotations.Schema; +using System.Data.Entity; +using System.Data.Entity.Infrastructure.Annotations; + +namespace Ex3_ModelManytoMany +{ + /// + public partial class EFModelOnetoMany : DbContext + { + #region DbSets + public virtual System.Data.Entity.DbSet Authors { get; set; } + public virtual System.Data.Entity.DbSet Books { get; set; } + #endregion DbSets + + #region Constructors + + partial void CustomInit(); + + /// + /// Default connection string + /// + public static string ConnectionString { get; set; } = @"Data Source=(localdb)\dbinstance;Initial Catalog=EFLocalDb;Integrated Security=True"; + /// + public EFModelOnetoMany() : base(ConnectionString) + { + Configuration.LazyLoadingEnabled = true; + Configuration.ProxyCreationEnabled = true; + System.Data.Entity.Database.SetInitializer(new EFModelOnetoManyDatabaseInitializer()); + CustomInit(); + } + + /// + public EFModelOnetoMany(string connectionString) : base(connectionString) + { + Configuration.LazyLoadingEnabled = true; + Configuration.ProxyCreationEnabled = true; + System.Data.Entity.Database.SetInitializer(new EFModelOnetoManyDatabaseInitializer()); + CustomInit(); + } + + /// + public EFModelOnetoMany(string connectionString, System.Data.Entity.Infrastructure.DbCompiledModel model) : base(connectionString, model) + { + Configuration.LazyLoadingEnabled = true; + Configuration.ProxyCreationEnabled = true; + System.Data.Entity.Database.SetInitializer(new EFModelOnetoManyDatabaseInitializer()); + CustomInit(); + } + + /// + public EFModelOnetoMany(System.Data.Common.DbConnection existingConnection, bool contextOwnsConnection) : base(existingConnection, contextOwnsConnection) + { + Configuration.LazyLoadingEnabled = true; + Configuration.ProxyCreationEnabled = true; + System.Data.Entity.Database.SetInitializer(new EFModelOnetoManyDatabaseInitializer()); + CustomInit(); + } + + /// + public EFModelOnetoMany(System.Data.Common.DbConnection existingConnection, System.Data.Entity.Infrastructure.DbCompiledModel model, bool contextOwnsConnection) : base(existingConnection, model, contextOwnsConnection) + { + Configuration.LazyLoadingEnabled = true; + Configuration.ProxyCreationEnabled = true; + System.Data.Entity.Database.SetInitializer(new EFModelOnetoManyDatabaseInitializer()); + CustomInit(); + } + + /// + public EFModelOnetoMany(System.Data.Entity.Infrastructure.DbCompiledModel model) : base(model) + { + Configuration.LazyLoadingEnabled = true; + Configuration.ProxyCreationEnabled = true; + System.Data.Entity.Database.SetInitializer(new EFModelOnetoManyDatabaseInitializer()); + CustomInit(); + } + + /// + public EFModelOnetoMany(System.Data.Entity.Core.Objects.ObjectContext objectContext, bool dbContextOwnsObjectContext) : base(objectContext, dbContextOwnsObjectContext) + { + Configuration.LazyLoadingEnabled = true; + Configuration.ProxyCreationEnabled = true; + System.Data.Entity.Database.SetInitializer(new EFModelOnetoManyDatabaseInitializer()); + CustomInit(); + } + + #endregion Constructors + + partial void OnModelCreatingImpl(System.Data.Entity.DbModelBuilder modelBuilder); + partial void OnModelCreatedImpl(System.Data.Entity.DbModelBuilder modelBuilder); + + /// + protected override void OnModelCreating(System.Data.Entity.DbModelBuilder modelBuilder) + { + base.OnModelCreating(modelBuilder); + OnModelCreatingImpl(modelBuilder); + + modelBuilder.HasDefaultSchema("dbo"); + + modelBuilder.Entity() + .ToTable("Authors") + .HasKey(t => t.AuthorId); + modelBuilder.Entity() + .Property(t => t.AuthorId) + .IsRequired() + .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity); + modelBuilder.Entity() + .Property(t => t.Firstname) + .HasMaxLength(125); + modelBuilder.Entity() + .Property(t => t.Lastname) + .HasMaxLength(125); + modelBuilder.Entity() + .HasMany(x => x.Books) + .WithRequired() + .Map(x => x.MapKey("AuthorBooksAuthorId")); + + modelBuilder.Entity() + .ToTable("Books") + .HasKey(t => t.BookId); + modelBuilder.Entity() + .Property(t => t.BookId) + .IsRequired() + .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity); + modelBuilder.Entity() + .Property(t => t.Title) + .HasMaxLength(255); + modelBuilder.Entity() + .Property(t => t.ISBN) + .HasMaxLength(75); + + OnModelCreatedImpl(modelBuilder); + } + } +} diff --git a/src/Examples/EF6/Ex3_ModelManytoMany/Generated_One2Many/EFModelOnetoManyDatabaseInitializer.generated.cs b/src/Examples/EF6/Ex3_ModelManytoMany/Generated_One2Many/EFModelOnetoManyDatabaseInitializer.generated.cs new file mode 100644 index 000000000..351c83bfd --- /dev/null +++ b/src/Examples/EF6/Ex3_ModelManytoMany/Generated_One2Many/EFModelOnetoManyDatabaseInitializer.generated.cs @@ -0,0 +1,24 @@ +//------------------------------------------------------------------------------ +// +// This code was generated from a template. +// +// Manual changes to this file may cause unexpected behavior in your application. +// Manual changes to this file will be overwritten if the code is regenerated. +// +// Produced by Entity Framework Visual Editor v3.0.7.2 +// Source: https://github.com/msawczyn/EFDesigner +// Visual Studio Marketplace: https://marketplace.visualstudio.com/items?itemName=michaelsawczyn.EFDesigner +// Documentation: https://msawczyn.github.io/EFDesigner/ +// License (MIT): https://github.com/msawczyn/EFDesigner/blob/master/LICENSE +// +//------------------------------------------------------------------------------ + +using System.Data.Entity; + +namespace Ex3_ModelManytoMany +{ + /// + public partial class EFModelOnetoManyDatabaseInitializer : CreateDatabaseIfNotExists + { + } +} diff --git a/src/Examples/EF6/Ex3_ModelManytoMany/Generated_One2Many/EFModelOnetoManyDbMigrationConfiguration.generated.cs b/src/Examples/EF6/Ex3_ModelManytoMany/Generated_One2Many/EFModelOnetoManyDbMigrationConfiguration.generated.cs new file mode 100644 index 000000000..9c3c4f967 --- /dev/null +++ b/src/Examples/EF6/Ex3_ModelManytoMany/Generated_One2Many/EFModelOnetoManyDbMigrationConfiguration.generated.cs @@ -0,0 +1,33 @@ +//------------------------------------------------------------------------------ +// +// This code was generated from a template. +// +// Manual changes to this file may cause unexpected behavior in your application. +// Manual changes to this file will be overwritten if the code is regenerated. +// +// Produced by Entity Framework Visual Editor v3.0.7.2 +// Source: https://github.com/msawczyn/EFDesigner +// Visual Studio Marketplace: https://marketplace.visualstudio.com/items?itemName=michaelsawczyn.EFDesigner +// Documentation: https://msawczyn.github.io/EFDesigner/ +// License (MIT): https://github.com/msawczyn/EFDesigner/blob/master/LICENSE +// +//------------------------------------------------------------------------------ + +using System.Data.Entity.Migrations; + +namespace Migrations +{ + /// + public sealed partial class EFModelOnetoManyDbMigrationConfiguration : DbMigrationsConfiguration + { + partial void Init(); + + /// + public EFModelOnetoManyDbMigrationConfiguration() + { + AutomaticMigrationsEnabled = true; + AutomaticMigrationDataLossAllowed = false; + Init(); + } + } +} diff --git a/src/Examples/EF6/Ex3_ModelManytoMany/ModelMany2Many.efmodel b/src/Examples/EF6/Ex3_ModelManytoMany/ModelMany2Many.efmodel new file mode 100644 index 000000000..49b51aff7 --- /dev/null +++ b/src/Examples/EF6/Ex3_ModelManytoMany/ModelMany2Many.efmodel @@ -0,0 +1,34 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/Examples/EF6/Ex3_ModelManytoMany/ModelMany2Many.efmodel.diagramx b/src/Examples/EF6/Ex3_ModelManytoMany/ModelMany2Many.efmodel.diagramx new file mode 100644 index 000000000..f0a42b64b --- /dev/null +++ b/src/Examples/EF6/Ex3_ModelManytoMany/ModelMany2Many.efmodel.diagramx @@ -0,0 +1,34 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/Examples/EF6/Ex3_ModelManytoMany/Program.cs b/src/Examples/EF6/Ex3_ModelManytoMany/Program.cs new file mode 100644 index 000000000..1017a6837 --- /dev/null +++ b/src/Examples/EF6/Ex3_ModelManytoMany/Program.cs @@ -0,0 +1,142 @@ +using System; +using System.Collections.Generic; +using System.Data.SqlClient; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace Ex3_ModelManytoMany +{ + static class Program + { + /// + /// The main entry point for the application. + /// + [STAThread] + static void Main() + { + Application.EnableVisualStyles(); + Application.SetCompatibleTextRenderingDefault(false); + + SetupLocalDb("mssqllocaldb", "EFVisualExamples"); + + Application.Run(new FrmModelOnetoMany()); + + } + + + + static void SetupLocalDb(string InstanceName = "mssqllocaldb", string DatabaseName = "EFVisualExamples") //This is a default instance name in local DB v13 + { + //Step 1: Islocaldb installed? + if (!CreateLocalDBInstance(InstanceName)) + { + + MessageBox.Show("CRITICAL ERROR: SqlLocalDb software is not installed!"); + + //Download SQL Server Express - LocalDB + // https://www.sqlshack.com/install-microsoft-sql-server-express-localdb/ + // https://www.microsoft.com/en-au/download/confirmation.aspx?id=101064 + // Microsoft SQL Server Express LocalDB supports silent installation. A user should download SqlLocalDB.msi and run the Command Prompt window as an administrator. Then, they should paste the following command: + // msiexec /i SqlLocalDB.msi /qn IACCEPTSQLLOCALDBLICENSETERMS = YES + string url = @"https://www.microsoft.com/en-au/download/confirmation.aspx?id=101064"; + Process.Start(url); + + Application.Exit(); + } + + //Step2: Create Database + + string connectionString = @"Data Source=(localdb)\" + InstanceName + $"; Integrated Security=True;"; + + if (!CheckDatabaseExists(connectionString, DatabaseName)) + { + //This is fixed -canot be changed + string UserPath = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); + + + SqlConnection connection = new SqlConnection(connectionString); + using (connection) + { + connection.Open(); + + string sql = $@" + CREATE DATABASE + {DatabaseName} + ON PRIMARY ( + NAME={DatabaseName}_data, + FILENAME = '{UserPath}\{DatabaseName}.mdf' + ) + LOG ON ( + NAME={DatabaseName}_log, + FILENAME = '{UserPath}\{DatabaseName}.ldf' + )"; + + SqlCommand command = new SqlCommand(sql, connection); + try + { + command.ExecuteNonQuery(); + } + catch (Exception ex) + { + MessageBox.Show($"CRITICAL ERROR: Database cannot be created\r\n{ex.ToString()}\r\nDoes Db exists in another instance?\r\n(Note: You cannot duplicate names across instances- requires unique name)"); + //You can debug using commandline + //>sqllocaldb info mssqllocaldb + + //https://docs.microsoft.com/en-us/sql/tools/sqllocaldb-utility?view=sql-server-ver15 + + string url = @"https://docs.microsoft.com/en-us/sql/relational-databases/express-localdb-instance-apis/command-line-management-tool-sqllocaldb-exe?view=sql-server-ver15"; + Process.Start(url); + + Application.Exit(); + } + + MessageBox.Show($" A New empty Local Database has been created successfully!\r\n\r\nSQLLOCALDB:{InstanceName}\r\nDATABASE:{DatabaseName}"); + } + } + } + + static bool CreateLocalDBInstance(string InstanceName) + { + // Lists all instances + // >sqllocaldb info + + // Start the child process. + Process p = new Process(); + // Redirect the output stream of the child process. + p.StartInfo.UseShellExecute = false; + p.StartInfo.RedirectStandardOutput = true; + p.StartInfo.FileName = "cmd.exe"; + p.StartInfo.Arguments = $"/C sqllocaldb c {InstanceName}"; //Create Local Db Instance + p.StartInfo.CreateNoWindow = true; + p.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; + p.Start(); + string sOutput = p.StandardOutput.ReadToEnd(); + p.WaitForExit(); + + //If LocalDb is not installed then it will return that 'sqllocaldb' is not recognized as an internal or external command operable program or batch file. + if (sOutput == null || sOutput.Trim().Length == 0 || sOutput.Contains("not recognized")) + return false; + if (sOutput.ToLower().Contains(InstanceName)) + return true; + return false; + } + + public static bool CheckDatabaseExists(string connectionString, string databaseName) + { + + using (var connection = new SqlConnection(connectionString)) + { + using (var command = new SqlCommand($"SELECT db_id('{databaseName}')", connection)) + { + connection.Open(); + var retval = command.ExecuteScalar(); + + return (retval != DBNull.Value); + } + } + } + } +} \ No newline at end of file diff --git a/src/Examples/EF6/Ex3_ModelManytoMany/Properties/AssemblyInfo.cs b/src/Examples/EF6/Ex3_ModelManytoMany/Properties/AssemblyInfo.cs new file mode 100644 index 000000000..fe2af63fc --- /dev/null +++ b/src/Examples/EF6/Ex3_ModelManytoMany/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("Ex3_ModelManytoMany")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("Ex3_ModelManytoMany")] +[assembly: AssemblyCopyright("Copyright © 2021")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("cd767834-7004-444d-b7d8-58ac359ed441")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/src/Examples/EF6/Ex3_ModelManytoMany/Properties/Resources.Designer.cs b/src/Examples/EF6/Ex3_ModelManytoMany/Properties/Resources.Designer.cs new file mode 100644 index 000000000..75731fc82 --- /dev/null +++ b/src/Examples/EF6/Ex3_ModelManytoMany/Properties/Resources.Designer.cs @@ -0,0 +1,70 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + + +namespace Ex3_ModelManytoMany.Properties +{ + /// + /// A strongly-typed resource class, for looking up localized strings, etc. + /// + // This class was auto-generated by the StronglyTypedResourceBuilder + // class via a tool like ResGen or Visual Studio. + // To add or remove a member, edit your .ResX file then rerun ResGen + // with the /str option, or rebuild your VS project. + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + internal class Resources + { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal Resources() + { + } + + /// + /// Returns the cached ResourceManager instance used by this class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Resources.ResourceManager ResourceManager + { + get + { + if ((resourceMan == null)) + { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Ex3_ModelManytoMany.Properties.Resources", typeof(Resources).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// + /// Overrides the current thread's CurrentUICulture property for all + /// resource lookups using this strongly typed resource class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Globalization.CultureInfo Culture + { + get + { + return resourceCulture; + } + set + { + resourceCulture = value; + } + } + } +} diff --git a/src/Examples/EF6/Ex3_ModelManytoMany/Properties/Resources.resx b/src/Examples/EF6/Ex3_ModelManytoMany/Properties/Resources.resx new file mode 100644 index 000000000..af7dbebba --- /dev/null +++ b/src/Examples/EF6/Ex3_ModelManytoMany/Properties/Resources.resx @@ -0,0 +1,117 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/src/Examples/EF6/Ex3_ModelManytoMany/Properties/Settings.Designer.cs b/src/Examples/EF6/Ex3_ModelManytoMany/Properties/Settings.Designer.cs new file mode 100644 index 000000000..14e37b627 --- /dev/null +++ b/src/Examples/EF6/Ex3_ModelManytoMany/Properties/Settings.Designer.cs @@ -0,0 +1,29 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + + +namespace Ex3_ModelManytoMany.Properties +{ + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")] + internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase + { + + private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); + + public static Settings Default + { + get + { + return defaultInstance; + } + } + } +} diff --git a/src/Examples/EF6/Ex3_ModelManytoMany/Properties/Settings.settings b/src/Examples/EF6/Ex3_ModelManytoMany/Properties/Settings.settings new file mode 100644 index 000000000..39645652a --- /dev/null +++ b/src/Examples/EF6/Ex3_ModelManytoMany/Properties/Settings.settings @@ -0,0 +1,7 @@ + + + + + + + diff --git a/src/Examples/EF6/Ex4_ModelInvoice/AccountingSystemModel.cs b/src/Examples/EF6/Ex4_ModelInvoice/AccountingSystemModel.cs new file mode 100644 index 000000000..6153a7d78 --- /dev/null +++ b/src/Examples/EF6/Ex4_ModelInvoice/AccountingSystemModel.cs @@ -0,0 +1 @@ + diff --git a/src/Examples/EF6/Ex4_ModelInvoice/AccountingSystemModel.efmodel b/src/Examples/EF6/Ex4_ModelInvoice/AccountingSystemModel.efmodel new file mode 100644 index 000000000..9d2d8a760 --- /dev/null +++ b/src/Examples/EF6/Ex4_ModelInvoice/AccountingSystemModel.efmodel @@ -0,0 +1,38 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/Examples/EF6/Ex4_ModelInvoice/AccountingSystemModel.efmodel.diagramx b/src/Examples/EF6/Ex4_ModelInvoice/AccountingSystemModel.efmodel.diagramx new file mode 100644 index 000000000..2088492c2 --- /dev/null +++ b/src/Examples/EF6/Ex4_ModelInvoice/AccountingSystemModel.efmodel.diagramx @@ -0,0 +1,40 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/Examples/EF6/Ex4_ModelInvoice/AccountingSystemModel.tt b/src/Examples/EF6/Ex4_ModelInvoice/AccountingSystemModel.tt new file mode 100644 index 000000000..d93318abc --- /dev/null +++ b/src/Examples/EF6/Ex4_ModelInvoice/AccountingSystemModel.tt @@ -0,0 +1,74 @@ +<#@ template inherits="Microsoft.VisualStudio.TextTemplating.VSHost.ModelingTextTransformation" debug="true" + hostSpecific="true" language="C#" compilerOptions="/langversion:latest"#> +<#@ CleanupBehavior processor="T4VSHost" CleanupAfterProcessingtemplate="true" #> +<#@ assembly name="System.Data.Entity.Design.dll" +#><#@ assembly name="EnvDTE" +#><#@ include file="EFDesigner.ttinclude" once="true" +#><#@ output extension=".cs" +#><#@ import namespace="System.Linq" +#><#@ import namespace="System" +#><#@ import namespace="System.Data.Entity.Design.PluralizationServices" +#><#@ import namespace="System.Globalization" +#><#@ import namespace="Sawczyn.EFDesigner.EFModel" +#><#@ EFModel processor="EFModelDirectiveProcessor" requires="FileName='AccountingSystemModel.efmodel'" +#><# + Manager manager = Manager.Create(Host, GenerationEnvironment); + manager.FileNameMarker = ModelRoot.FileNameMarker; + + if (ModelRoot.Classes.Any()) + { + manager.StartHeader(false); + Output("//------------------------------------------------------------------------------"); + Output("// "); + Output("// This code was generated from a template."); + Output("//"); + Output("// Manual changes to this file may cause unexpected behavior in your application."); + Output("// Manual changes to this file will be overwritten if the code is regenerated."); + Output("//"); + Output("// Produced by Entity Framework Visual Editor v" + ModelRoot.DSLVersion); + Output("// Source: https://github.com/msawczyn/EFDesigner"); + Output("// Visual Studio Marketplace: https://marketplace.visualstudio.com/items?itemName=michaelsawczyn.EFDesigner"); + Output("// Documentation: https://msawczyn.github.io/EFDesigner/"); + Output("// License (MIT): https://github.com/msawczyn/EFDesigner/blob/master/LICENSE"); + Output("// "); + Output("//------------------------------------------------------------------------------"); + NL(); + + EFModelGenerator generator; + + switch (ModelRoot.EntityFrameworkVersion) + { + case EFVersion.EF6: + { + generator = new EF6ModelGenerator(this); + break; + } + + case EFVersion.EFCore: + { + switch ((int)ModelRoot.GetEntityFrameworkPackageVersionNum()) + { + case 2: + generator = new EFCore2ModelGenerator(this); + break; + + case 3: + generator = new EFCore3ModelGenerator(this); + break; + + default: + generator = new EFCore5ModelGenerator(this); + break; + } + break; + } + + default: + throw new InvalidOperationException("Unsupported Entity Framework version"); + } + + generator.Generate(manager); + } + + manager.Process(true); +#> \ No newline at end of file diff --git a/src/Examples/EF6/Ex4_ModelInvoice/App.config b/src/Examples/EF6/Ex4_ModelInvoice/App.config new file mode 100644 index 000000000..193aecc67 --- /dev/null +++ b/src/Examples/EF6/Ex4_ModelInvoice/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/src/Examples/EF6/Ex4_ModelInvoice/Ex4_ModelInvoice.csproj b/src/Examples/EF6/Ex4_ModelInvoice/Ex4_ModelInvoice.csproj new file mode 100644 index 000000000..1c2fd3d4f --- /dev/null +++ b/src/Examples/EF6/Ex4_ModelInvoice/Ex4_ModelInvoice.csproj @@ -0,0 +1,112 @@ + + + + + Debug + AnyCPU + {2B46097A-AE7A-4F87-A7D8-EC7F9865A681} + WinExe + Ex4_ModelInvoice + Ex4_ModelInvoice + v4.8 + 512 + true + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + True + True + AccountingSystemModel.tt + + + Form + + + FrmInvoice.cs + + + + + + + + + + FrmInvoice.cs + + + ResXFileCodeGenerator + Resources.Designer.cs + Designer + + + True + Resources.resx + + + + AccountingSystemModel.efmodel + + + SettingsSingleFileGenerator + Settings.Designer.cs + + + True + Settings.settings + True + + + + + + + + 6.4.4 + + + + + TextTemplatingFileGenerator + AccountingSystemModel.cs + + + + + + + + \ No newline at end of file diff --git a/src/Examples/EF6/Ex4_ModelInvoice/FRmInvoice.Designer.cs b/src/Examples/EF6/Ex4_ModelInvoice/FRmInvoice.Designer.cs new file mode 100644 index 000000000..6413e9a8f --- /dev/null +++ b/src/Examples/EF6/Ex4_ModelInvoice/FRmInvoice.Designer.cs @@ -0,0 +1,101 @@ + +namespace Ex4_ModelInvoice +{ + partial class FrmInvoice + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + this.btnInvoice = new System.Windows.Forms.Button(); + this.txtDebug = new System.Windows.Forms.TextBox(); + this.label1 = new System.Windows.Forms.Label(); + this.txtConnection = new System.Windows.Forms.TextBox(); + this.SuspendLayout(); + // + // btnInvoice + // + this.btnInvoice.Location = new System.Drawing.Point(37, 135); + this.btnInvoice.Name = "btnInvoice"; + this.btnInvoice.Size = new System.Drawing.Size(243, 87); + this.btnInvoice.TabIndex = 0; + this.btnInvoice.Text = "Create and read back Invoice header and detail"; + this.btnInvoice.UseVisualStyleBackColor = true; + this.btnInvoice.Click += new System.EventHandler(this.button1_Click); + // + // txtDebug + // + this.txtDebug.Location = new System.Drawing.Point(347, 135); + this.txtDebug.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + this.txtDebug.Multiline = true; + this.txtDebug.Name = "txtDebug"; + this.txtDebug.Size = new System.Drawing.Size(421, 266); + this.txtDebug.TabIndex = 11; + // + // label1 + // + this.label1.AutoSize = true; + this.label1.Location = new System.Drawing.Point(33, 49); + this.label1.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); + this.label1.Name = "label1"; + this.label1.Size = new System.Drawing.Size(167, 20); + this.label1.TabIndex = 10; + this.label1.Text = "Sql Server Connection"; + // + // txtConnection + // + this.txtConnection.Location = new System.Drawing.Point(33, 73); + this.txtConnection.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + this.txtConnection.Name = "txtConnection"; + this.txtConnection.Size = new System.Drawing.Size(734, 26); + this.txtConnection.TabIndex = 9; + this.txtConnection.Text = "..."; + // + // FrmInvoice + // + this.AutoScaleDimensions = new System.Drawing.SizeF(9F, 20F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(800, 450); + this.Controls.Add(this.txtDebug); + this.Controls.Add(this.label1); + this.Controls.Add(this.txtConnection); + this.Controls.Add(this.btnInvoice); + this.Name = "FrmInvoice"; + this.Text = "Ex 4: Invoice - Header and Detail"; + this.Load += new System.EventHandler(this.FRmInvoice_Load); + this.ResumeLayout(false); + this.PerformLayout(); + + } + + #endregion + + private System.Windows.Forms.Button btnInvoice; + private System.Windows.Forms.TextBox txtDebug; + private System.Windows.Forms.Label label1; + private System.Windows.Forms.TextBox txtConnection; + } +} + diff --git a/src/Examples/EF6/Ex4_ModelInvoice/FRmInvoice.cs b/src/Examples/EF6/Ex4_ModelInvoice/FRmInvoice.cs new file mode 100644 index 000000000..0e2909eb5 --- /dev/null +++ b/src/Examples/EF6/Ex4_ModelInvoice/FRmInvoice.cs @@ -0,0 +1,113 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Data.Entity; +using System.Data.Entity.Validation; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace Ex4_ModelInvoice +{ + public partial class FrmInvoice : Form + { + public FrmInvoice() + { + InitializeComponent(); + } + + private void button1_Click(object sender, EventArgs e) + { + + txtDebug.Text = "TestOne2One()\r\n"; + + using (AccountingSystemModel db = new AccountingSystemModel()) + { + // Perform data access using the context + db.Database.Log = Console.Write; + db.Database.CommandTimeout = 120; + + // --------------- + // TODO: I dont know where to set AutomaticMigrationDataLossAllowed = true in tool? + // So doing a delete and recreate + db.Database.Log = Console.Write; + + + txtDebug.Text += "\r\nEx 4: Invoice - Header and Detail\r\n----------------\r\n"; + + db.Database.Delete(); + txtDebug.Text += "Deleted DB\r\n"; + + db.Database.CreateIfNotExists(); + txtDebug.Text += "Created DB\r\n"; + // ------------- + + + InvoiceHeaders invHeader = db.InvoiceHeaders.Create(); + InvoiceDetails invDetails = db.InvoiceDetails.Create(); + + invHeader.Total = 150M; + + invDetails.ItemDescription = "New Item"; + invDetails.Price = 75M; + invDetails.Quantity = 2; + + //Associate Header and Details + invHeader.InvoiceDetails.Add(invDetails); + db.InvoiceHeaders.Add(invHeader); + + try + { + db.SaveChanges(); + } + catch (System.Data.Entity.Validation.DbEntityValidationException dbEx) + { + Exception raise = dbEx; + foreach (DbEntityValidationResult validationErrors in dbEx.EntityValidationErrors) + { + foreach (DbValidationError validationError in validationErrors.ValidationErrors) + { + string message = string.Format("{0}:{1}", + validationErrors.Entry.Entity.ToString(), + validationError.ErrorMessage); + // raise a new exception nesting the current instance as InnerException + raise = new InvalidOperationException(message, raise); + } + } + throw raise; + + } + + //Read it back + DbSet records = db.InvoiceHeaders; + + foreach (InvoiceHeaders record in records) + { + txtDebug.Text += String.Format("Invoice Id {0} - Total: {1}", record.Id, record.Total) + "\r\n"; ; + + txtDebug.Text += "--- Detail --\r\n"; + + //TODO: Error? There is already an open DataReader associated with this Command which must be closed first. + //Cannot figure out how to get detail data? + //foreach (InvoiceDetails details in record.InvoiceDetails) + //{ + // // txtDebug.Text += String.Format("Invoice Id {0} - Total: {1} | Details Desc:{2} Qty:{3} Price:{4} Total:{5}", record.Id, record.Total, details.ItemDescription, details.Quantity, details.Price, details.Total) + "\r\n"; + //} + + } + } + } + + private void FRmInvoice_Load(object sender, EventArgs e) + { + + using (AccountingSystemModel db = new AccountingSystemModel()) + { + txtConnection.Text = db.Database.Connection.ConnectionString; + } + } + } +} diff --git a/src/Examples/EF6/Ex4_ModelInvoice/FRmInvoice.resx b/src/Examples/EF6/Ex4_ModelInvoice/FRmInvoice.resx new file mode 100644 index 000000000..1af7de150 --- /dev/null +++ b/src/Examples/EF6/Ex4_ModelInvoice/FRmInvoice.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/src/Examples/EF6/Ex4_ModelInvoice/GeneratedAccountingModel/AccountingSystemModel.generated.cs b/src/Examples/EF6/Ex4_ModelInvoice/GeneratedAccountingModel/AccountingSystemModel.generated.cs new file mode 100644 index 000000000..ea7d797a2 --- /dev/null +++ b/src/Examples/EF6/Ex4_ModelInvoice/GeneratedAccountingModel/AccountingSystemModel.generated.cs @@ -0,0 +1,143 @@ +//------------------------------------------------------------------------------ +// +// This code was generated from a template. +// +// Manual changes to this file may cause unexpected behavior in your application. +// Manual changes to this file will be overwritten if the code is regenerated. +// +// Produced by Entity Framework Visual Editor v3.0.7.2 +// Source: https://github.com/msawczyn/EFDesigner +// Visual Studio Marketplace: https://marketplace.visualstudio.com/items?itemName=michaelsawczyn.EFDesigner +// Documentation: https://msawczyn.github.io/EFDesigner/ +// License (MIT): https://github.com/msawczyn/EFDesigner/blob/master/LICENSE +// +//------------------------------------------------------------------------------ + +using System; +using System.Collections.Generic; +using System.Linq; +using System.ComponentModel.DataAnnotations.Schema; +using System.Data.Entity; +using System.Data.Entity.Infrastructure.Annotations; + +namespace Ex4_ModelInvoice +{ + /// + public partial class AccountingSystemModel : DbContext + { + #region DbSets + public virtual System.Data.Entity.DbSet InvoiceDetails { get; set; } + public virtual System.Data.Entity.DbSet InvoiceHeaders { get; set; } + #endregion DbSets + + #region Constructors + + partial void CustomInit(); + + /// + /// Default connection string + /// + public static string ConnectionString { get; set; } = @"Data Source=(localdb)\dbinstance;Initial Catalog=EFLocalDb;Integrated Security=True"; + /// + public AccountingSystemModel() : base(ConnectionString) + { + Configuration.LazyLoadingEnabled = true; + Configuration.ProxyCreationEnabled = true; + System.Data.Entity.Database.SetInitializer(new AccountingSystemModelDatabaseInitializer()); + CustomInit(); + } + + /// + public AccountingSystemModel(string connectionString) : base(connectionString) + { + Configuration.LazyLoadingEnabled = true; + Configuration.ProxyCreationEnabled = true; + System.Data.Entity.Database.SetInitializer(new AccountingSystemModelDatabaseInitializer()); + CustomInit(); + } + + /// + public AccountingSystemModel(string connectionString, System.Data.Entity.Infrastructure.DbCompiledModel model) : base(connectionString, model) + { + Configuration.LazyLoadingEnabled = true; + Configuration.ProxyCreationEnabled = true; + System.Data.Entity.Database.SetInitializer(new AccountingSystemModelDatabaseInitializer()); + CustomInit(); + } + + /// + public AccountingSystemModel(System.Data.Common.DbConnection existingConnection, bool contextOwnsConnection) : base(existingConnection, contextOwnsConnection) + { + Configuration.LazyLoadingEnabled = true; + Configuration.ProxyCreationEnabled = true; + System.Data.Entity.Database.SetInitializer(new AccountingSystemModelDatabaseInitializer()); + CustomInit(); + } + + /// + public AccountingSystemModel(System.Data.Common.DbConnection existingConnection, System.Data.Entity.Infrastructure.DbCompiledModel model, bool contextOwnsConnection) : base(existingConnection, model, contextOwnsConnection) + { + Configuration.LazyLoadingEnabled = true; + Configuration.ProxyCreationEnabled = true; + System.Data.Entity.Database.SetInitializer(new AccountingSystemModelDatabaseInitializer()); + CustomInit(); + } + + /// + public AccountingSystemModel(System.Data.Entity.Infrastructure.DbCompiledModel model) : base(model) + { + Configuration.LazyLoadingEnabled = true; + Configuration.ProxyCreationEnabled = true; + System.Data.Entity.Database.SetInitializer(new AccountingSystemModelDatabaseInitializer()); + CustomInit(); + } + + /// + public AccountingSystemModel(System.Data.Entity.Core.Objects.ObjectContext objectContext, bool dbContextOwnsObjectContext) : base(objectContext, dbContextOwnsObjectContext) + { + Configuration.LazyLoadingEnabled = true; + Configuration.ProxyCreationEnabled = true; + System.Data.Entity.Database.SetInitializer(new AccountingSystemModelDatabaseInitializer()); + CustomInit(); + } + + #endregion Constructors + + partial void OnModelCreatingImpl(System.Data.Entity.DbModelBuilder modelBuilder); + partial void OnModelCreatedImpl(System.Data.Entity.DbModelBuilder modelBuilder); + + /// + protected override void OnModelCreating(System.Data.Entity.DbModelBuilder modelBuilder) + { + base.OnModelCreating(modelBuilder); + OnModelCreatingImpl(modelBuilder); + + modelBuilder.HasDefaultSchema("dbo"); + + modelBuilder.Entity() + .ToTable("InvoiceDetails") + .HasKey(t => t.Id); + modelBuilder.Entity() + .Property(t => t.Id) + .IsRequired() + .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity); + modelBuilder.Entity() + .Property(t => t.ItemDescription) + .HasMaxLength(255); + + modelBuilder.Entity() + .ToTable("InvoiceHeaders") + .HasKey(t => t.Id); + modelBuilder.Entity() + .Property(t => t.Id) + .IsRequired() + .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity); + modelBuilder.Entity() + .HasMany(x => x.InvoiceDetails) + .WithRequired() + .Map(x => x.MapKey("InvoiceHeadersInvoiceDetailsId")); + + OnModelCreatedImpl(modelBuilder); + } + } +} diff --git a/src/Examples/EF6/Ex4_ModelInvoice/GeneratedAccountingModel/AccountingSystemModelDatabaseInitializer.generated.cs b/src/Examples/EF6/Ex4_ModelInvoice/GeneratedAccountingModel/AccountingSystemModelDatabaseInitializer.generated.cs new file mode 100644 index 000000000..eafb1eb36 --- /dev/null +++ b/src/Examples/EF6/Ex4_ModelInvoice/GeneratedAccountingModel/AccountingSystemModelDatabaseInitializer.generated.cs @@ -0,0 +1,24 @@ +//------------------------------------------------------------------------------ +// +// This code was generated from a template. +// +// Manual changes to this file may cause unexpected behavior in your application. +// Manual changes to this file will be overwritten if the code is regenerated. +// +// Produced by Entity Framework Visual Editor v3.0.7.2 +// Source: https://github.com/msawczyn/EFDesigner +// Visual Studio Marketplace: https://marketplace.visualstudio.com/items?itemName=michaelsawczyn.EFDesigner +// Documentation: https://msawczyn.github.io/EFDesigner/ +// License (MIT): https://github.com/msawczyn/EFDesigner/blob/master/LICENSE +// +//------------------------------------------------------------------------------ + +using System.Data.Entity; + +namespace Ex4_ModelInvoice +{ + /// + public partial class AccountingSystemModelDatabaseInitializer : MigrateDatabaseToLatestVersion + { + } +} diff --git a/src/Examples/EF6/Ex4_ModelInvoice/GeneratedAccountingModel/AccountingSystemModelDbMigrationConfiguration.generated.cs b/src/Examples/EF6/Ex4_ModelInvoice/GeneratedAccountingModel/AccountingSystemModelDbMigrationConfiguration.generated.cs new file mode 100644 index 000000000..76e5c150e --- /dev/null +++ b/src/Examples/EF6/Ex4_ModelInvoice/GeneratedAccountingModel/AccountingSystemModelDbMigrationConfiguration.generated.cs @@ -0,0 +1,33 @@ +//------------------------------------------------------------------------------ +// +// This code was generated from a template. +// +// Manual changes to this file may cause unexpected behavior in your application. +// Manual changes to this file will be overwritten if the code is regenerated. +// +// Produced by Entity Framework Visual Editor v3.0.7.2 +// Source: https://github.com/msawczyn/EFDesigner +// Visual Studio Marketplace: https://marketplace.visualstudio.com/items?itemName=michaelsawczyn.EFDesigner +// Documentation: https://msawczyn.github.io/EFDesigner/ +// License (MIT): https://github.com/msawczyn/EFDesigner/blob/master/LICENSE +// +//------------------------------------------------------------------------------ + +using System.Data.Entity.Migrations; + +namespace Migrations +{ + /// + public sealed partial class AccountingSystemModelDbMigrationConfiguration : DbMigrationsConfiguration + { + partial void Init(); + + /// + public AccountingSystemModelDbMigrationConfiguration() + { + AutomaticMigrationsEnabled = true; + AutomaticMigrationDataLossAllowed = false; + Init(); + } + } +} diff --git a/src/Examples/EF6/Ex4_ModelInvoice/GeneratedAccountingModel/InvoiceDetails.generated.cs b/src/Examples/EF6/Ex4_ModelInvoice/GeneratedAccountingModel/InvoiceDetails.generated.cs new file mode 100644 index 000000000..e3306ad31 --- /dev/null +++ b/src/Examples/EF6/Ex4_ModelInvoice/GeneratedAccountingModel/InvoiceDetails.generated.cs @@ -0,0 +1,105 @@ +//------------------------------------------------------------------------------ +// +// This code was generated from a template. +// +// Manual changes to this file may cause unexpected behavior in your application. +// Manual changes to this file will be overwritten if the code is regenerated. +// +// Produced by Entity Framework Visual Editor v3.0.7.2 +// Source: https://github.com/msawczyn/EFDesigner +// Visual Studio Marketplace: https://marketplace.visualstudio.com/items?itemName=michaelsawczyn.EFDesigner +// Documentation: https://msawczyn.github.io/EFDesigner/ +// License (MIT): https://github.com/msawczyn/EFDesigner/blob/master/LICENSE +// +//------------------------------------------------------------------------------ + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using System.Linq; +using System.Runtime.CompilerServices; + +namespace Ex4_ModelInvoice +{ + public partial class InvoiceDetails + { + partial void Init(); + + /// + /// Default constructor. Protected due to required properties, but present because EF needs it. + /// + protected InvoiceDetails() + { + Init(); + } + + /// + /// Replaces default constructor, since it's protected. Caller assumes responsibility for setting all required values before saving. + /// + public static InvoiceDetails CreateInvoiceDetailsUnsafe() + { + return new InvoiceDetails(); + } + + /// + /// Public constructor with required data + /// + /// + public InvoiceDetails(global::Ex4_ModelInvoice.InvoiceHeaders _invoiceheaders0) + { + if (_invoiceheaders0 == null) throw new ArgumentNullException(nameof(_invoiceheaders0)); + _invoiceheaders0.InvoiceDetails.Add(this); + + Init(); + } + + /// + /// Static create function (for use in LINQ queries, etc.) + /// + /// + public static InvoiceDetails Create(global::Ex4_ModelInvoice.InvoiceHeaders _invoiceheaders0) + { + return new InvoiceDetails(_invoiceheaders0); + } + + /************************************************************************* + * Properties + *************************************************************************/ + + /// + /// Identity, Indexed, Required + /// Unique identifier + /// + [Key] + [Required] + [System.ComponentModel.Description("Unique identifier")] + public long Id { get; set; } + + /// + /// Max length = 255 + /// Desc + /// + /// + /// Item description + /// + [MaxLength(255)] + [StringLength(255)] + [System.ComponentModel.Description("Desc")] + public string ItemDescription { get; set; } + + public decimal? Price { get; set; } + + public decimal? Quantity { get; set; } + + public decimal? Total { get; set; } + + /************************************************************************* + * Navigation properties + *************************************************************************/ + + } +} + diff --git a/src/Examples/EF6/Ex4_ModelInvoice/GeneratedAccountingModel/InvoiceHeaders.generated.cs b/src/Examples/EF6/Ex4_ModelInvoice/GeneratedAccountingModel/InvoiceHeaders.generated.cs new file mode 100644 index 000000000..1b9beb75a --- /dev/null +++ b/src/Examples/EF6/Ex4_ModelInvoice/GeneratedAccountingModel/InvoiceHeaders.generated.cs @@ -0,0 +1,64 @@ +//------------------------------------------------------------------------------ +// +// This code was generated from a template. +// +// Manual changes to this file may cause unexpected behavior in your application. +// Manual changes to this file will be overwritten if the code is regenerated. +// +// Produced by Entity Framework Visual Editor v3.0.7.2 +// Source: https://github.com/msawczyn/EFDesigner +// Visual Studio Marketplace: https://marketplace.visualstudio.com/items?itemName=michaelsawczyn.EFDesigner +// Documentation: https://msawczyn.github.io/EFDesigner/ +// License (MIT): https://github.com/msawczyn/EFDesigner/blob/master/LICENSE +// +//------------------------------------------------------------------------------ + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using System.Linq; +using System.Runtime.CompilerServices; + +namespace Ex4_ModelInvoice +{ + public partial class InvoiceHeaders + { + partial void Init(); + + /// + /// Default constructor + /// + public InvoiceHeaders() + { + InvoiceDetails = new System.Collections.Generic.HashSet(); + + Init(); + } + + /************************************************************************* + * Properties + *************************************************************************/ + + /// + /// Identity, Indexed, Required + /// Unique identifier + /// + [Key] + [Required] + [System.ComponentModel.Description("Unique identifier")] + public long Id { get; set; } + + public decimal? Total { get; set; } + + /************************************************************************* + * Navigation properties + *************************************************************************/ + + public virtual ICollection InvoiceDetails { get; private set; } + + } +} + diff --git a/src/Examples/EF6/Ex4_ModelInvoice/Program.cs b/src/Examples/EF6/Ex4_ModelInvoice/Program.cs new file mode 100644 index 000000000..e1876de85 --- /dev/null +++ b/src/Examples/EF6/Ex4_ModelInvoice/Program.cs @@ -0,0 +1,141 @@ +using System; +using System.Collections.Generic; +using System.Data.SqlClient; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace Ex4_ModelInvoice +{ + static class Program + { + /// + /// The main entry point for the application. + /// + [STAThread] + static void Main() + { + Application.EnableVisualStyles(); + Application.SetCompatibleTextRenderingDefault(false); + + SetupLocalDb("mssqllocaldb", "EFVisualExamples"); + + Application.Run(new FrmInvoice()); + + } + + + static void SetupLocalDb(string InstanceName = "mssqllocaldb", string DatabaseName = "EFVisualExamples") //This is a default instance name in local DB v13 + { + //Step 1: Islocaldb installed? + if (!CreateLocalDBInstance(InstanceName)) + { + + MessageBox.Show("CRITICAL ERROR: SqlLocalDb software is not installed!"); + + //Download SQL Server Express - LocalDB + // https://www.sqlshack.com/install-microsoft-sql-server-express-localdb/ + // https://www.microsoft.com/en-au/download/confirmation.aspx?id=101064 + // Microsoft SQL Server Express LocalDB supports silent installation. A user should download SqlLocalDB.msi and run the Command Prompt window as an administrator. Then, they should paste the following command: + // msiexec /i SqlLocalDB.msi /qn IACCEPTSQLLOCALDBLICENSETERMS = YES + string url = @"https://www.microsoft.com/en-au/download/confirmation.aspx?id=101064"; + Process.Start(url); + + Application.Exit(); + } + + //Step2: Create Database + + string connectionString = @"Data Source=(localdb)\" + InstanceName + $"; Integrated Security=True;"; + + if (!CheckDatabaseExists(connectionString, DatabaseName)) + { + //This is fixed -canot be changed + string UserPath = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); + + + SqlConnection connection = new SqlConnection(connectionString); + using (connection) + { + connection.Open(); + + string sql = $@" + CREATE DATABASE + {DatabaseName} + ON PRIMARY ( + NAME={DatabaseName}_data, + FILENAME = '{UserPath}\{DatabaseName}.mdf' + ) + LOG ON ( + NAME={DatabaseName}_log, + FILENAME = '{UserPath}\{DatabaseName}.ldf' + )"; + + SqlCommand command = new SqlCommand(sql, connection); + try + { + command.ExecuteNonQuery(); + } + catch (Exception ex) + { + MessageBox.Show($"CRITICAL ERROR: Database cannot be created\r\n{ex.ToString()}\r\nDoes Db exists in another instance?\r\n(Note: You cannot duplicate names across instances- requires unique name)"); + //You can debug using commandline + //>sqllocaldb info mssqllocaldb + + //https://docs.microsoft.com/en-us/sql/tools/sqllocaldb-utility?view=sql-server-ver15 + + string url = @"https://docs.microsoft.com/en-us/sql/relational-databases/express-localdb-instance-apis/command-line-management-tool-sqllocaldb-exe?view=sql-server-ver15"; + Process.Start(url); + + Application.Exit(); + } + + MessageBox.Show($" A New empty Local Database has been created successfully!\r\n\r\nSQLLOCALDB:{InstanceName}\r\nDATABASE:{DatabaseName}"); + } + } + } + + static bool CreateLocalDBInstance(string InstanceName) + { + // Lists all instances + // >sqllocaldb info + + // Start the child process. + Process p = new Process(); + // Redirect the output stream of the child process. + p.StartInfo.UseShellExecute = false; + p.StartInfo.RedirectStandardOutput = true; + p.StartInfo.FileName = "cmd.exe"; + p.StartInfo.Arguments = $"/C sqllocaldb c {InstanceName}"; //Create Local Db Instance + p.StartInfo.CreateNoWindow = true; + p.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; + p.Start(); + string sOutput = p.StandardOutput.ReadToEnd(); + p.WaitForExit(); + + //If LocalDb is not installed then it will return that 'sqllocaldb' is not recognized as an internal or external command operable program or batch file. + if (sOutput == null || sOutput.Trim().Length == 0 || sOutput.Contains("not recognized")) + return false; + if (sOutput.ToLower().Contains(InstanceName)) + return true; + return false; + } + + public static bool CheckDatabaseExists(string connectionString, string databaseName) + { + + using (var connection = new SqlConnection(connectionString)) + { + using (var command = new SqlCommand($"SELECT db_id('{databaseName}')", connection)) + { + connection.Open(); + var retval = command.ExecuteScalar(); + + return (retval != DBNull.Value); + } + } + } + } +} \ No newline at end of file diff --git a/src/Examples/EF6/Ex4_ModelInvoice/Properties/AssemblyInfo.cs b/src/Examples/EF6/Ex4_ModelInvoice/Properties/AssemblyInfo.cs new file mode 100644 index 000000000..c8254302b --- /dev/null +++ b/src/Examples/EF6/Ex4_ModelInvoice/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("Ex4_ModelInvoice")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("Ex4_ModelInvoice")] +[assembly: AssemblyCopyright("Copyright © 2021")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("2b46097a-ae7a-4f87-a7d8-ec7f9865a681")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/src/Examples/EF6/Ex4_ModelInvoice/Properties/Resources.Designer.cs b/src/Examples/EF6/Ex4_ModelInvoice/Properties/Resources.Designer.cs new file mode 100644 index 000000000..7ab375334 --- /dev/null +++ b/src/Examples/EF6/Ex4_ModelInvoice/Properties/Resources.Designer.cs @@ -0,0 +1,70 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + + +namespace Ex4_ModelInvoice.Properties +{ + /// + /// A strongly-typed resource class, for looking up localized strings, etc. + /// + // This class was auto-generated by the StronglyTypedResourceBuilder + // class via a tool like ResGen or Visual Studio. + // To add or remove a member, edit your .ResX file then rerun ResGen + // with the /str option, or rebuild your VS project. + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + internal class Resources + { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal Resources() + { + } + + /// + /// Returns the cached ResourceManager instance used by this class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Resources.ResourceManager ResourceManager + { + get + { + if ((resourceMan == null)) + { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Ex4_ModelInvoice.Properties.Resources", typeof(Resources).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// + /// Overrides the current thread's CurrentUICulture property for all + /// resource lookups using this strongly typed resource class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Globalization.CultureInfo Culture + { + get + { + return resourceCulture; + } + set + { + resourceCulture = value; + } + } + } +} diff --git a/src/Examples/EF6/Ex4_ModelInvoice/Properties/Resources.resx b/src/Examples/EF6/Ex4_ModelInvoice/Properties/Resources.resx new file mode 100644 index 000000000..af7dbebba --- /dev/null +++ b/src/Examples/EF6/Ex4_ModelInvoice/Properties/Resources.resx @@ -0,0 +1,117 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/src/Examples/EF6/Ex4_ModelInvoice/Properties/Settings.Designer.cs b/src/Examples/EF6/Ex4_ModelInvoice/Properties/Settings.Designer.cs new file mode 100644 index 000000000..28632a9f5 --- /dev/null +++ b/src/Examples/EF6/Ex4_ModelInvoice/Properties/Settings.Designer.cs @@ -0,0 +1,29 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + + +namespace Ex4_ModelInvoice.Properties +{ + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")] + internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase + { + + private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); + + public static Settings Default + { + get + { + return defaultInstance; + } + } + } +} diff --git a/src/Examples/EF6/Ex4_ModelInvoice/Properties/Settings.settings b/src/Examples/EF6/Ex4_ModelInvoice/Properties/Settings.settings new file mode 100644 index 000000000..39645652a --- /dev/null +++ b/src/Examples/EF6/Ex4_ModelInvoice/Properties/Settings.settings @@ -0,0 +1,7 @@ + + + + + + + diff --git a/src/Examples/EF6/Ex5_Store/App.config b/src/Examples/EF6/Ex5_Store/App.config new file mode 100644 index 000000000..193aecc67 --- /dev/null +++ b/src/Examples/EF6/Ex5_Store/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/src/Examples/EF6/Ex5_Store/EFCRM.cs b/src/Examples/EF6/Ex5_Store/EFCRM.cs new file mode 100644 index 000000000..6153a7d78 --- /dev/null +++ b/src/Examples/EF6/Ex5_Store/EFCRM.cs @@ -0,0 +1 @@ + diff --git a/src/Examples/EF6/Ex5_Store/EFCRM.efmodel b/src/Examples/EF6/Ex5_Store/EFCRM.efmodel new file mode 100644 index 000000000..f438418c0 --- /dev/null +++ b/src/Examples/EF6/Ex5_Store/EFCRM.efmodel @@ -0,0 +1,255 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/Examples/EF6/Ex5_Store/EFCRM.efmodel.diagramx b/src/Examples/EF6/Ex5_Store/EFCRM.efmodel.diagramx new file mode 100644 index 000000000..4d5e2cb17 --- /dev/null +++ b/src/Examples/EF6/Ex5_Store/EFCRM.efmodel.diagramx @@ -0,0 +1,178 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/Examples/EF6/Ex5_Store/EFCRM.tt b/src/Examples/EF6/Ex5_Store/EFCRM.tt new file mode 100644 index 000000000..ca0177d23 --- /dev/null +++ b/src/Examples/EF6/Ex5_Store/EFCRM.tt @@ -0,0 +1,74 @@ +<#@ template inherits="Microsoft.VisualStudio.TextTemplating.VSHost.ModelingTextTransformation" debug="true" + hostSpecific="true" language="C#" compilerOptions="/langversion:latest"#> +<#@ CleanupBehavior processor="T4VSHost" CleanupAfterProcessingtemplate="true" #> +<#@ assembly name="System.Data.Entity.Design.dll" +#><#@ assembly name="EnvDTE" +#><#@ include file="EFDesigner.ttinclude" once="true" +#><#@ output extension=".cs" +#><#@ import namespace="System.Linq" +#><#@ import namespace="System" +#><#@ import namespace="System.Data.Entity.Design.PluralizationServices" +#><#@ import namespace="System.Globalization" +#><#@ import namespace="Sawczyn.EFDesigner.EFModel" +#><#@ EFModel processor="EFModelDirectiveProcessor" requires="FileName='EFCRM.efmodel'" +#><# + Manager manager = Manager.Create(Host, GenerationEnvironment); + manager.FileNameMarker = ModelRoot.FileNameMarker; + + if (ModelRoot.Classes.Any()) + { + manager.StartHeader(false); + Output("//------------------------------------------------------------------------------"); + Output("// "); + Output("// This code was generated from a template."); + Output("//"); + Output("// Manual changes to this file may cause unexpected behavior in your application."); + Output("// Manual changes to this file will be overwritten if the code is regenerated."); + Output("//"); + Output("// Produced by Entity Framework Visual Editor v" + ModelRoot.DSLVersion); + Output("// Source: https://github.com/msawczyn/EFDesigner"); + Output("// Visual Studio Marketplace: https://marketplace.visualstudio.com/items?itemName=michaelsawczyn.EFDesigner"); + Output("// Documentation: https://msawczyn.github.io/EFDesigner/"); + Output("// License (MIT): https://github.com/msawczyn/EFDesigner/blob/master/LICENSE"); + Output("// "); + Output("//------------------------------------------------------------------------------"); + NL(); + + EFModelGenerator generator; + + switch (ModelRoot.EntityFrameworkVersion) + { + case EFVersion.EF6: + { + generator = new EF6ModelGenerator(this); + break; + } + + case EFVersion.EFCore: + { + switch ((int)ModelRoot.GetEntityFrameworkPackageVersionNum()) + { + case 2: + generator = new EFCore2ModelGenerator(this); + break; + + case 3: + generator = new EFCore3ModelGenerator(this); + break; + + default: + generator = new EFCore5ModelGenerator(this); + break; + } + break; + } + + default: + throw new InvalidOperationException("Unsupported Entity Framework version"); + } + + generator.Generate(manager); + } + + manager.Process(true); +#> \ No newline at end of file diff --git a/src/Examples/EF6/Ex5_Store/EFModelFirstDemo-master.zip b/src/Examples/EF6/Ex5_Store/EFModelFirstDemo-master.zip new file mode 100644 index 0000000000000000000000000000000000000000..8e6333d6c026f8d31e6307911be35f8e79c15c41 GIT binary patch literal 24923 zcmb@tV{~R;_a*woww;PqaZ<5u+qR90ZQEwWPAYbu*tTs{(slcGzqfz?9=Gp!$9vC* zGtQTNKI}Qyo@>puwt_SmI4t1*dio7vWdHle|9D{oU;v_Gvi2sXHe!}e&MqRRw)Wp` z4V_&~ofuSAAOIk~i8k5_|6@7ye_xIfmtxlh3IHs@000#KhvoF4z4t}dp| z|N2?8s;vDwBYgLb~DFx+6U$w(y&nTuazwP*I1&6#dgtO`^&iT(k*l-LAHU z2IbPmTI({N19kAAhw(5wLNB;HHDUmQ4NQB>0Y~X!E=9ysK9g4`7YrWgYqXD=VPgZS z_g9#9E!K#K*N*mL|;~1oa7Qf zSH-+R4yoNbD!(iKmz2y}ccr$$C@!x^yf{8aFP?c;_Q^cV%XOHNDSB*-pa|MKY!aEd zts84J+yI*vOCB2+5vJ7|P$gtAS zlL)N1^(LxzeO>7r6>-s>ALo+O>;7o*e93|m61G}9-1JW@<>fA~AdK8YtWdA-Zn6bA zS_#jm88Ug*n9Y>X?y!5vXz<0~t5r;Lu!AGtny&G7@Gv@T8g=l%Ltjl)a_f+G4WRB~ zxJ`6oRQ`aycsq$(UYNkX4q&TJGVGDai9g+i-7BWHBhdbp*h$oi0b`R}#qMXt-hO7T znP8)>obb{0u9h&U)A-u_F>}QK&j285+@9Zq0sv-_0RWQ!j{vYVx3hOL{TKOD)YqL3 zT2OqC)rrZ~Nn+HC)mwf<+!vo;t#yd9oNrdvP-9923R?((Liju12L0wO195WMR8b-i zXk(w*ER%n}xU7$hlGE<{nO1uoDeJ2*In`wm)3RZw`8~zKUSn2Tm5Em87f)zcRbqE{ z+bCusTB^5Vz0pK8d-vW`29KUg*gWS#%`maVIr<)1?3JSG=iD6+%cXE$Qjra$oa^9iS93b{-Q%Eh<}ik9iy_j3c`V`ORZ%ww_^rfWNgO5bN&`kj4T9OIUfn+z%g*F`Ig{9wpt&Otgt!Grd0^AOxX(whJ7bJxzky~Qmf3&IMxX;nB^4NNP zh3z81$wdUj$0a3+?{NP4e2307Od9ND8Ql#nb|;5f7IRr#aa5IE4ra$Mc0TBuXT9jd z@*7CNA`Ve&%1izs&>7V+!W@JHN-FbtUf0Q!HI^F!eKmI~O zL-Lns^zn3|f%Qr^GROE6f%_G)yBKVFvA4ZfzHAlj^}84S5#CIp zv!+T7ejzIj)Z8WYc;PiL7VHW`vD_$~x^l`H?65~XV7>T7?fPBw|LF~UF&K2{frh+Zua zL-K~|T3&7n-$3BVaGl}$mE!4FF&;SI?A7lHAG8OTe4118xvUE-Tc}w7x!iqFo?K=e z`Vev*%Mw98PuY<^%lS6)m)j0M2A` zN%K$mxS>o%vPjq)h_Y(jkGfQ;0ShcWs`{#>j$D^M_It)i*pB6RjPHzt%BSpuyMm8R zE-B^u+)i7C(SucJiX>Sp%%#cG4OI_o-;`$uI6$m#X0U-XiIwxaCH`CC0d$JE0k9c3q;(T%=#stweQezPDF_O6`^?_tV!DV+Zn5e4^SRWGeCIiZ-l;hqTm7 z>7Bo{_X51`dm*{cPUFY!Fk{tC=xh~JU4zpj4Iss5o0TOOB;5zzUc!>PSOJix1zLS< z_Q)Be$wcL#3s^P1u*7ReD~7BjD@l(}c-JxS&)0J`dBp zr#cLww20fEH}i3R{9f)ZF7X$|QX#}j$qM34odYl-KPY~W| zi_+_bC5Nr5wD-uuZwfq4uq}+y(b;$DSPvAi89YMK@tuP!6ur=;hR>Ubgq{#Uj0|#` z!y))p%)hvJB<|$R3_Z!O`m^rfa5m6F3b1k27#@uhf3|n{FpDk0$-O_5XTeJIFb~_~ zNeQbi)*HCrBsiC&cPTI?5mR2nhd8wG-kE$!&rK08vY962rs%iSao|lE>{vS#cyYduQ{a z$q?27Z{K;Yn^as9*8YIvU?;Ge0&5xBN>0|)?M z1P%bu{U1_=|C)l+JKNa(D{074l8sv@M&=FEH*8Oq*h++qjtX_VTc( zv$?mu4jQ%bqieBFX9cKu>n6w`nILo*c6T2R2k3|g@o&TkaPnZLWD4*EON+I1+25}S zI1tRD;KwkKjZ3~u(ta4%=xO0n0S1wEf!Jx(bm-rSg+LXDoGM`Js4B7m((&^ z?n}1XUfwvLEaAx}?C>%P+PFD~s%4l0IVf?8HIzo%CB9Ks82o}&Qwn@yikJP9kF=rD zT27aaKkez?&!`?0(a%QPc(s0pJZW>N-UqzOcU?aV0H;V&Vt9M}v9%#;^z_X{elOnd zS4}O~pI|1TUNQ@=S;o`{;uoYyo#Q--w;v3NXeBU6-8~ldT6r0}g@K~>HaYnd6EQwq ziZ7D`(ovsEuiMr*_(d$W({=e)jE=h_wg8L6Uu z1BML*YzsrB3QETv-6dW`pqx8o|A~wokCV7#8F%zzD!7PceMv<0b%!oH^Qco$Z!r-5 zXaZhroA$C;yAI_JKNntZ)sKzahQ7w-qRe?HjVd#pF%2|^EdwrOtmr~gk~aouck=9o z?YG6xbwbc+*J@`&i!Y;m%i(WYrCR3SE-H9rVn}eX8_!LsX3=kb31Cy-Jw%<9pefg_ zy2vyNYrY_O>Q1e}x=PJM?0gva4Auy8A5{(8e6LU3qopI9LU-ZeH0{Z;(DCRuvB%O^AVvy(z;^k$ZU9x9WWx{PXO^a&`0}Z`$lFV*D9{`2s zg&;V7!n>Ei8bdTI{FVA7f(Z+(xWy;zo%;gMuIV}!MQIIHGlbOu^Y&J(3^r3=65q#XEOAZ0!z*2if-9{!sh>ggPwMH7v z9aF0O?ni~=(-U7xP9PAfhjDSxNO;aj(7~M_j&G9JdlrU`-cxQ*Ca12(peMoK(Ir*V z*<6Mgol4@39QV*jzgc_D4ux1SN{=&;i3-%Sm$GSnyEXjwKL3Ydbv4?dP@tP+E9R7# z#+>JJORk97?m*;QHxAZTgtpZiDTUW{e%dx-*fqb7{Kk(mPTYHB4R3l!LklsjPNhOa=oTo2COR|29T)CUM z>0K7XYDfrW>Q%9h~f~{&h4iVz1lni9PuK?iWgFNC=!_OIz|7`o3B&$qqXA6o6$+G|IY z;QiXb_mK1k$7_sN2lj30NJ&*fg75jA^NHW@kF8%DQn@3P5Gqisq*9X_r>H+xI7Liu;Rm3a%WN4Ck>^$QJcAX#ia?ySLq(DuSh`{In=7m1QSNR z3W#f%|Az16K4Q@vokLJ`@L+&CWkVY#cc`nRF53=G7^&6EqO@kS)!o%l17Y>;Tf~K= zh|jUL-*2y(Ds|e!GsPNBJC*ksr_RlqwDo4M=bbv|8S4d_ZAFn#%7i;=CBtH|d*tj- z-W9bY&TrTbwe%YRlM^oqXCI(%{)mXgVvzs38e!f|Q%SIa&@paL0C|`khgfZT02e0o z>*SDZCe3lJ;Z>IEx)*rP4Ivt=t&|xZpfua8*-YD0!Ahn01%|PgRUnLU6AtVqqSr%0 zJOVmrTdI(DK#MlUr{0Dk+TQv!2JS#R(IDr{$Cga**C9UyWmA3dE>F5aK$+fw08S-G z#eDc&GFj4rd;tl_YoJA%lrBWnu}#8Bt`kLYjPccNp_(b#7BA~Y0?(S+e$g1_e=a6zbdjx*b$(V*x}aSahwPD)t@Dcy6|X1Zi@xe+I+kE zWIJ~@raTh730p*}&1JeRnj+cbcfZe|y?-+W6qMb(^_6{F4sawRZ&=6IzoTxLp{L!*~Y z#5AILXOi`$;3&zL4{B9trGP%J4}9;sdbo2CTjeG*&KT4-3s%iUH32}>=u`PJF>Eco zVKs6o#-LruPC@aveKA2fi~t=zt(?;?TO%YGi~>o09kucrsJDTvDhXe(1UD+%`a25x zIJ1btJ_!qDE8}w}=lO)=$J)#l#vKhj-D~X*s88u#QGU|Fwlx-*I_9-1(6Yb^S3i~^ zBW=&Mh1=>HJc132mQyr!^Ja&g)`d8=R>gaxiR1nE2aRE-K9zvel7-TfIApd!;z4ih zIMF}2Pubwr6oPfv?X%o=sd1GfDNfx^3#ZTAms^H4&wuKjd@hOc@lN`iKvOz>UTv>zaDM1Zpp(6a!v zKmKF5b;+`Yg8?Li+vjx<1xf`qB8U+OlhKs>tWzf?RaUs^2AKS7iACW;m)aF6kL~;5 z!>!;@G7g<#vJV8r(5`(}1!^BD4I*i?fvW}UN}#vIq9y~W`2(cblM%$+Z?GnjOPOwM z=0pJm_`b3J-!#~%E_8WC9($K6VPANMgiTPKdhs9>>~$Rz?6w#Zla6lt804CrRuo|^ zpv~?}-s+rVCATW>7b|G&$0If|)kcb$Vu@%T7qqKjEMY73(2H!m7EIwhYrYBgQt1TN zr=w2l&=tpK>j?PfadU9DL-{s2%vFqIE3E?k`pUQxMTFyN$1VkCMMVfE6^8tvpY8HI zK4sUOlkXaTdTjv9a%zivrXM|uv#XpR5&nsXjwBGh>@OZ-f8|W%-@)Ub{TmS>dSQDz z7gLXaf}=cT_qXrT^G+R}J12bUopdk9CAg%7MXK(OdPk1m=iRh~~2E@!6XU|B!3vklv>AxgZWiquKa96{m#>p#&`Lgac z7cZGkYj!B#g#M`GdeIm@rIpt!H0m*7^YZv&{TjCx{Do?TAY^>Q=u!}w5{xJ+TbV0* zy{rHIaG<|_PH&fR{LGZsUpxVeRoy>nUD=?)yL@K;fI|0c0%LRv#|h}fb558TIbSb0 z*BKds)b3mwV9ygzA8ZtMW2U4w@c9jUJzl`O-ji0Ec{B1npdyUOrjS^!Ce#h3AZY2Z zr%e%9*uF|rUi?af)P zjY0h`iTzI5BfY0{QB1TJ8qU-;0{rju&@n$67tkE-fiEeb>s6(R6hI_*s8`9XVCEYG8iS?Kc9w@DM&xvQ6 zWYa{jv=|tI<3NWC$=A%W>~zG)A-w^)CA7wVNV1EiiF1Bj~f zOG(Y64Vy8FhD~d=vi&AG?eAw*oZdOW5VTLr|eaCB-sL!TgmsGI6wEcWaFW11s;!O*wQ*6AJM~ zzO3S?u2_FHb{LW%^wEaVdk+U*=pE&HFGY;Gi^N?UJ$+k5J4l1g^YiVkb0}y??bAZ~ z-#M_Cs~%ysyc1(f!i#rl!+I< zb00kg?OVeKxdBA^-ioD`YpkDgd^bmPw?Tjsy9#w2 zAC5Egx6YxXP=!6}#ttZGls&MJ4L>kYoXO_Oo|>pU8nbi6pw8i{xJtp0jsjcihs=>(P822;ouv<7{i5&Z0Dgwzj?9ehMdc+&pl2$X(600j_?%AqJ zFTx!*kkKjy(OBER9sA*_%YC+GOS{82p<@)bKHkh4F#c+QgU=Wf@QFNKnTECH0g2bY zE&yo=34o8&r2-ldJna-L2tGFB`vd3(?-Pr#BH`~!yJuSSo~IYOsld;f)+i9%Pk$_f z>chE||9-;BOBHzxYJ2X&7v~iwlJ@Q?omGH5Dzb~2T5ke{-5F_<-Po3Z|3K9*D#3Dm z`}a+mdF->>6>r=; z9=LW^u;_wbJT;M+CD);^T=d_rZcIP>sAKm^e|PV$%RlzIv$l*w^igNoAWo()rlGta zplCXcR2tp;Kdfqcx>uco&eL-mFdrh`%3G|YuTPqwoDuoz*7c(_z_44cWsj3Yi6z%+ z9in21SqYM3fy<=#z+^SWQJ4fDD*297l=gHAth9fEV1$xPa6Dsjnn}j9q{MRsteRUY zPDEL&P29ZQ$~ycZ`0xh(str27wkNjPg0J;!+kJUHqG;l70@WwD!9`v7mHV!*w*OMJ z&FD?$amy=THhF1HAI!002BnY4?c-&{(;cwp{}r?gQ!n%_jVTjHL5l5hoG z3>g2~w+}CbM=@f|L<*|!B@&PFnuCBJg#jfr zz65uC$4(J?{jI+Cj#j~n!M$y;CVn}%p7P*O(R{dzRwvP45u)R2J7))NZV@NiTr%Uw zq=9NZnty5Dnlbad!S{nqfGL78p0ILN*PKJ&UZh#ZhYPTm?6~hqj!}M#k^Sh`xMHSX zuVC0iBa3c9H!((4&<=v6CR86#JPFN#`ArT^ugTrzU~D4UPvRb8prT&L`@tCdA}s5B zMl?D|kT+dogj0i@@lO~>f?1o;592MPTR2R@YO|cVK|ZD{X-L)^Csadgf>KJTRnw%C zTZtskw4aH?ajnLQK#b`YiK0ff8+)oTmIiLx8tc1uH=0u*{b@1RIa4dG7rA{-%0GUm>cjEQJlrR$mNEHT*}vObw?pB31`Gws@{)K|>kwVD4sHvcZBmNHUw zq4J5Zw!4U(=cJc#nIo>ZBZs8WHW=gHsrddds&kfHHn`mUB2;>)|ml}v%nY=&aSkVNcH8OpBe zuww@Ar!og&&9~I(PXDI9VnJ3`rb`JEvMJp;TCxcE!af;4q$!Nos5G3On?N(I@bDK# z%c;mrC92(~Eha=ICCmJYKNig2u}H_E-L+0L1vNACIJr^%E;(VCiXGB7m`o?gYk9QQ z9U|OwoKuU513064=^t!=jM@&rZj~(&U|NrK7&!GiA>Z$ zX{7T5AFMNzwkUEVJ6%3?7C0Z+=OtuapQfp1(HEd1*1eJrHE*&(s-BoVVYlF4L`pu3 zMT>cl4bOfeK#Tq^oA=oFlluhYV+lk68$A6_u3L>4;ZNMDT!;Zs3MozE(J{Oy7eb~6i0ww=yGJNLBZ3c>j_{mknNcJWPG0owa#`P*;QS+qbH911P zKzsT*oz-nSgyrd8N@W75>5RPPM;~L~oH*br-QgG=o+>#5r7JUy`T1#^j^EwO?fl~i ze|3?lOcw7NLYh;#o9E`G0g_S}x@;~pSJ!5Jl+XJ2GxAPg7bF)KT796kXT4ep^;foH zYm&Q7?*8o33=gRnkNm75IX0sQFqXZwn`M)OeY+d&%Fgp|f1K98yNuV-IH61Z=INUrlhn&Qlr!K}!rV~FG*2^pz{IeRdq_qjRi9DfL_$;Rq2I3FNk1De-k zOZXj{DRNr?Z_yGHiFGW`Es2n=*-Pu4lz@ms;78sF1A_s?8gMt!Z9ZqW(yxtJ1+GP8$LQ^G~kq5qD7z@eI7u7AGr%~+V` zp`I7zCp)ODAWub?Dek)5f@QS|)&MZK*FP*d!6h^P*q3Qu1%~F9pkM-)A2Hcf*N4YOTlzW%WhfP8M zi&{~>oR7)m{ssv+sy1@U)f4?qJbIHRB8?Q;+9xH%YK|UBVT8qZlJ_

QECmcX4h{c zb|_mKui4O&^VaPMzuox}`JQK$&f9r{?(6TBkvO4F>+W^p)uZ1JNlTlfHogRceB(d9D)t>Q~Jf9b!-s ztj^m#Z6ArWi4d*8IjD>$j)3itX*TAMd-!}LVz4lHY4~Ad#5$^(zZh_KHq~P>_#z*=f9(~KWJBwV}Y;F!U2fVz=ucZ?U~)3Y2QaX z5|QI&5Jqmg8Suo2dqkX8#?1R*mt4_5?bi%4T2^_isIaQOZqPFt`g6!Xty0O;;-o6* zil(`~9e@6f!>Tv_S;5E;jNv};<0#tOA+fzwt?J5v)ZMabzBE_!$keZ$hypvyfXu)Z zU9n2}X@0k->U@i|#7ihT$>pU(?Y|RSeigQYXP9{`VO+sW)@MW%e6b>q@<;`4LbF_O z_^jq+kMnE<=Dg}ufD_|_g4-(9;7V5EDpn)>-t*B~0!3d_RDMUpc{$T@lM@BENZAC8 zmS%;G2w$C;h3()_inQxZpUYE6nvGhE?d7DnOJ)AOgY-5! z`>w!(R;&4E_Do>oQ7eavT@K7OH`G=6XTB_s=HKQ+*t^d3 zH5J-iOzoJ`p1hwCH!a~ct<09xD^vn#8 z+FojZeS!SbD#F^gpeX%o9%B48b4C9n^H9Xp`R~}Osnh>z?V2jp+iftyZ{B0r-|ulr zm)Tj;W1(Bjf=bQ|MbXW+;A*pyz0!ZS!2c=!6rz6hv8DHiit;(|_BqH~-d{m+Eh)(etu5tO@?i3RigkE);sVKq}-iuZbo?+_nNz#Ej2+$9w^ zDkjMs{|&WqQCir|B^QOZ^gG zn-2x^Zp{O~O0;PT9^Hs?t{ka$F9-Icxfs+fH{XwZsH(g^`y}W_`;<~T=K}ON-D(-`^?st$Z-f-5f#iI!#jIccXlK(Fe-l_{>cb``Fz&$ zzjOXoe_6rvA2H&8ZKTK7qXaR+i+Y#7!1-hCGzfOkYrA^Lj2h{!^ghTTW9lqZC<7xZ;#Qx>?~Nnx<%GvCO2FSwB4s^&f7U-uA zG(p2TNx0}`DHNuQ*Mm1MM97?*lt{JDbv4xWEEd)A*RY|7h<_Gi6?JTR4eN+x$^dP3 z&~z25tyXRaA$?jsg8p+W)Mke(9v}gLQ5pb%??2iKQxjW{e>td& zTAOz3?C3q$$`&0~kb_clhWvurB+WTX>1bH>>xOC3BHaBCKN4W~de-QlB)mfsP$d&k zsTE@pY<>g?-};0dhlL#%JxuHS>391@kRIb4QOP9Ld-HKQ6QsXbB2%o_Ywt{*PG7yB z|4?TP*QYl>h`Udj_7y)yJq6dDD>HtE*}s^(kN*NU_7`(JIi{BS;c-w_4;8r3$-(_T z#LfSF;`00!v#;ap?sYb4mlHdciwH|2U2MODbj<@STPkpBMR#+3L(9x;z6Xu}Wmbsf7a zdu5-lSJ0riH@=^42J|kA5Q~DCkb+B_=o|T-nqnf^1<4{ZhgegkiGBV$>^aMr+M6*V z=nHQ5FJ*mAzTVHzo$o4#Kk4{0I7)rrDoPV$31{u zj!J6xkS@wDW0X){IYmyjPpNg)hyRmc$Y)O|g<%+H3|zRxt~du}36b;|3dPU#fO12W zJOj=93UP>J?96_63YXGhc033#UeJ`|+F7APWY*wS7Zqznt4`qAZz5wed2?_r^1WUZ zyVPFc!RPTRu9b7z>Cq-C&aCt?oW5tnP&niyV@9$ zdkjPeK>wCyN&>%N&0u&T1M8#ig~a?2oJ|(D&qeTh;Zpi%Vys5qJWiGB5rb%N7%F{-jkcG8u?v=BreJD>aAgEE)h<*)PCmf zxMO7kW!ILw5z3cK>W9!IF-S1_H=NE4Gg%$^(ZQsPe=ifzDfVs#9Xn`y4Z+Je9fF7* zl0BfCxp}X)PtCWj9+zf*Jgij=zgsD%X0*hrmY$APo3>a+T+Xu8jupzlatl`fkfMz2 z_q{}prlz>tQ(Y}-8L%Whw9#oOGmmz=E!;FtJ=!>_m+~Xj)N zz;U8P!3?el_$1;Rb9+1 zNC_9iFW!c?8+M6s3YmpZV7O7wJL)RwHe}akW1HYqWQKO8cAimV8GUh8oe2ewBKc)Z zqI>bp^~hn;R7MpH&u=|X0?ER?O<%qTw>=nd#GEhn7%L-M@+E!NnoXnp>E7sK!`MN4 zZ3!ORMn$tEQB8Z~TB{)&8izs|ogz3Ui;3hoE%4Gpj<6jgo~wh9m})kO_F4cf6m2po zUJ^bevu$hILaQmiy_}8qcIUFtJGsn3MP15onyKv@&zgETIWX6%>j)m>D0RE{s2Fcc zfbR{xP@n0JH$1n*d}(oS;^X?+U-=8~8Mp{*rjW_bM#NTu9T$JN8ZUdp5u~ti-$xo; ze8{c~y^z0g6LVdE9#)2+khD$UxQJ?B?WXVyEzkEo$*VA!hB zYu3Hx6C<}GUliJ&cNd%IE)>-@3+f5&B{WnXWmYn`Uiaex3$9^%5H>g9mYrw<&z44E z_Yi#$8=!t8zcpEFhk);qc@x38p$1t&ZE|K0;LIlgp&uVKDwbC!)UeWhNn)+z#R-KX zga^Vlwl4D#3`)PYKj8i;tR0V7kBNWti^;!Pr`Ufitn?<9hUQL&w*L~?5@lWaenxcP zXLX(TVkB*xe3^d66EiYF#z_6R=I$VhCUR@0x9dxTf$PB&!j_FrZy;~$af|y$HRerl zNQxLG87v;Sf-`AxF1g9!9WlkopBzHi$Bn5EIJ@&THO=$cHMfc1Fd5vf7fM#I_!x}^ ziCv6K2lNMGiWKm+?6~5rkrtYAZ`?EM2%w`tVo_RiT(})E?ghlBIhbfl<OOKe82mR1G*<<}3=qZx&{no9hKOsTgmD)T{FF*pMNt-(vYN~?5 zf?509_J!Y;=d!twjZrOilUv!l(w zpdV7VwJ#Jv{sjI?x3`+ZVrwrx_AR{FOCV_qjEKn$9d98YiPEgAe?GSd=%-@Y%6H>4 zm2)>XPP5!khR+?6>wG?v@6zK^=-q(?4{ceGav&E5u^n%b1f+!rJ^Jh8_=!umZhpEY zY}wCwm%+)M1b%prWw<zQ3~#_XOCLEuTJgY%WwxBWs+2Fz~?o zC-!0M@#H-kY-Q0K5ARn@`1s+9OY@m412GkOO3sM;RTuXig*1>=u_E=yE-{>g786v+ zqSkI0nQf(VS%na^mD#w!l~w&De3fxE(J2n^%`zmF`;>mp1w_ARiVgV2;(ni@V-)K^ zbdgC(kag6>QCcmvR!`4gubv$T&5rjW{En&j0&85)D7N&BJ=O9jGNEqVSPrx9v zXPo3DXAyCK(fH+0hGq`id;14XFnqQ_Vx}&!WP))3!BW>iyJyi-Z@X%2m@B9h+`|@= z)g4j;Yc$1-pPd^k2NSzAr{aj@c`DhA10+lEA=)>qqG?N(}3NE;g-LKHqfz~_0W5xSov6{Aml1+O@NRu*LpB~7i$9!{}bf* z3Y3Up#oA(Qk}ICLi|>FW^SAu;P*Wt+sX9X^zvm{FQcE;Xs<+X8jbs639+j5l%)~TB zHFUjgCN>K=1m&={69;Hln8D@vD4}YqcF1e7QCEf57GWxPC`>@EV2b(YF51ApGWvjc zRRfLnkf+huVvPjEZ=Mp8J~IqqT4!7(3>I6eg-UktY6ivKSNeH?kZYvz1f!su4Fc8; zTL)!Bo7$o>c1W7D9}XovC9+wcY1KuB^59zeVG}`err-%S#oCJ{k~_FkRtG3XfFg!z z`_Dxjzn-&0MSf~MnBJZ_3@(~7?Z20g;M5D0^;>b5!Y0&!y%9+Uf839!A_Bf)J-12x z*E=QfkNI~7r~tsJ{(oB5{V%g1hxn^@>k@aKe=y*|;3cAkD1pRqFXJ2yJhOKA=A@MO z@i^E`3yE#Q3AluE@FV&yNbi#GaN3Jd?*>W9_?*r#b>EXVUDaJ(Rg=Enr~RIZeqN)S z)JG2layX_>jys4UZhQ(aXT(o9x$Vdea8TB=$lsIbCpxmm3`5x^qzw9cw1vzUnc%0P z?a35jn<2{OLR?2u#YUdz^TS34ZimitcuYu67-?c6zN*BN#myb`A`EkOcQ&)hC3QL6 zkwhip^oBT60v0$OdfesbVIt%U=@??iNO*su#Er;)aoI^^gnDf%Oe>)xL5@Vrk3D9-TXk`wM_SiMeZl27Ko(OY$GO`zesbg zEk)xT?Ux5%yC`#%86E{MGiKC;F4QmC1s|P_@PHY&C5|ovKno)@s8@)i9E4lNPB2cP zx8u6EaTNC|umUV-Gr6|FJUKn&8!Wswk(`-joLJLII!LIN+$A5ZVRoEm{P91*{!stz>?WQZ7?IOCafWguBb>e^W#xf83hzeN2?0YX4TwVW|HhFm7XPll+ zB@6J*rptB)Yoy|(N-#|ggpUkA;1?VENS7I4rr!#4lyqW5*Oju*9D%*@#@KNrZ&=<{ zWi8sG1z9k7)(%_m4cbnSuR)GML4^(p6x;0gbx79n?zw+;hN3*<0Q=T?sBH72-2CIt z&?P5G6kooA6q#w3Ky>-809<+Udr7c%= zafNjOTB5kNK>MHy*daweHCz`4Uuh#RmOSwZWoY?XR3UmZ0w^fC`ECGngth)a(<_AW z@pY$DN=kL?ktL42UVLl3b~gDfTP;Q;fGy63F*@_A_A+3`jNIW-O$X}R(p-@?X~=%d za?Zf*U9hLtE}jrR1FxZyz^qoM7WD`Fc-IF%H64wor7pG%*jXv3c}sZhPB= zqt~8$8n{$%qUB2IoH&f<=7vp5_C)TJ#MlSKUG8re$o%!oHR@g>PB6yNt--Tx+2;8j43qBC^9Fb6ep#rhz6Wf*X?h8*_x#owMc{`r z75lW*qNtlQ4v0}2CaW(AfmciyTIGhzTvYox`TJ(a76isg?mxrWj>)VFdNj zPF{eV52q62=efY?13RQ2Wg06Mlv~1q8dFU!83RRCkT}6S#h^WAi}nyr)MRoe9t9mq^ZfoR|S1TVWHQSSyHsdw=p zI|usgP><$ekKA-A@Gw8t1QB^xj)yIAVbfotI0(M>nC8`Fm%|${6&24hjwoT57vXQb zaA~)W7fTd5vl6nGx>8L4fEbfwAN`u(;G3{mU70tiNMNf#KADwpSLI9*pR=zjzb&0S z9xwr|yw~~IuF2kx_doj5{b+TbBMZ?w@J*uUw4JoKr=3&1Yr2Z91MY&0Ts?{3GivMM z>p#tduOnk&@7zcAjj_1P1Iw}yr3LmT=^9U9*EQ#+L=5X}z!3Nk zgrH{ncxS;;DMji*5h)_# zjn8o(o*aGSde2)K`=32B=5NonlRekk>s#OCy&`_-C;b^Z7igWsMwBbo`hf~r+xpK zUx)P8(*m@&JNtr^g#PR6M7P`?{!vgPX0!#CSeSczc(6Y{#`nr+VEouL%WJserlEw5 z=M1dhb$WX09(u?>?s3JlU8FZ2tg##gVd?C~Yj+{grxe@~m<$^q<+ z*LM?kdiRAwca=Y_F%FX(ChMo$zhBRgl8^&nIq(&slNw|jWa|~~Y$j`9&N(}|z*^s2 zDJW6}Dazi9rJruy=pDBhcp^l5+p4ruljGQ@aNaFKahfqcp}@xPObMHfHZ;C`6MB_S zqg!&;@cRldb;=I%rUI)II;luf8fP{3$#iQ8u_;hJPUetNryNA)8FQPwmwxmC9D zz75r^Z-B{U)7y*vM;lk3KdeAI)>tk(rly3|${p(MHG@zQPP0?0*GdbC^{h%H8@dVs zK}29%dYf~`UnW~~)n@A%SIT!E=|Dy=cAyD{Xis|&@}_rPU{ zZ0Ax@_9Y0O#%vR_E=itKstUp5eMqrv!?8pu#|5f)d<+xRk&f|SnI{a6!{)eMA(ueS z=osDMJA|2fvaG_RA767Hnf!_N)JOTV+*-y8TY|MRG&9{2dL49kBwP4Ev&IB7C6gte zOzq>J^J=GGa^O_=xsx~5cGy9{-jrlDDnbOvEne&)y>WNzGg)-|?G)|?wb%nrNp_ga zN86ka@6y9O{EJ*lQ^#2*7L4>P!c6Y$=@{0me(}r{kLi2Ifk^gSQ<4Qu#t=Jt3QYs8 zyyixos0w2Bn>x3nMnQmEf_`viotq@yw(2!%XQ+SGmJDEoiom-KuEr4ttsR z%&`YdKy!#a#YkYj;eR zDO9!VKfO>&F5P;nI!iI12#--GgL*(%xuc&2ZV}<9Y7|aP)pNSnsH%Y0%*ynm9)J}8 zSchF&L27;7LY^tHJG*?#g_=N9AjJrrTTM2ff5x0AqrHouHhS+%H$H zsbKX(XCslIAz%a$KCaR>T;B)TKvCspt(cL-U*|&JUzYeFqGbMzC6Ps&)VP%LL!qZD zT0&lJ^d6qPlg<4vZrK~<(c$phOcm`1bCv7uJJ*@yF*bdx7x#vFc$3$IcF`4tO~v8o zVlEFlJBUVN0#-;A?8nqLNhAbmTCST$QBIki6Y=Zo3DfTiebLBbqxPSCJ(^lEN+9y! z<}NjPukE!Yw#{JSCE86?l);mW@ZsEmfe`khg~FPT3T13V_Dj^E zGl#I-Yjlpc8j~}{{Z(H@vB2Km^E&hl$ixAv}3T&pf%yTgNH9 z(R3cO_zKbie@-)n6+M2KuG>E^TCc$*AHe;5u>2Bd1w;8(NvF>mh*_{Kx+w0dt461f?iC4j#fXIH~ZFiSxy zTQ5JAx93%5$Oqro`#MFp%Bd%4PyKAW+bAk$zr`%$g~E;diW;{)1`JfrE(`&3KqNXU zX-AvO&E03F@gH?_KBo!wEajjl2+;H&(71_~r;6uQWel<2sfTeSTqd`+OXp;^)$>%K zJ+W}^!pK=`iaE((gxrCioEb>wTuNj7K!aEiqC|6_{fxE z{^w1~sQXcGVe<2&bV=h;;ijs_$%A`%w7e00uTx`|M3)dGWhLDhy@q$bm~6{2j==UEcZ+2XZXR6eib+c>=I93PjiA^vd)p2v^8Zj-U0lO2@)=#9$~DZv?k@)6UM zk_$P2NCQDMKhaBOp9#XEYCt5LWF;aGkk19Y$nt_$UwZ~=B=gY~l2Xzl zl#-w?HQVCGMKBXkZ@6Ci0pZNnhiWtGFOEafI+<4?{rKbVuD(D z=6trNY`-Y7$xJ`O(|c;-Z(7>W77d7s=4{#@TIYV9$pqa0+zgKuicgP zeO?+Ml2R>LoB?vWm-*G$x)0BOFOM~Wo~J4Cg%iaThkRj&WJy-%7k6) z@mmfS2A=NU)(3u6rd;cnCw*=}PWWE7z%NgvNkRRY2t9s7q_W?6(BX;G2fF-^4ixM? zf)HW4b&0U$F7^4r2~#l8@nA?rF8r&YmC9;2Z>(Y^h=8U#sqiX22_Vq9Zd`hqu1fsG#GQ?5l5Zyh2G91p|$dghWKqNEL0)GA>mEfh|nTCAw<>Z#sjbM~!n z%j%H0p|BW!NZ^Rwx~eKvLCOBEIe52ox3lH;F}d{&c-AEIDWkQ$nHJW-o&TFwVNmRi*sZxcd14f^%?LWU{r>J5BisW+a^-BE|*1=ylcfDCic12>S0 zc#mF@nGn;1bcPw!y+E7sH%yI)T&n@X&rQAz=E*sALoav1^sfTW zrCy$b4u%?kRk)CkF0r7-3^eI~%V5CqhGd=u(5Yu6aXWt5CILW$q`Z&IKyXhiU*6toi}LDHg=<C%P#m@QQ#Y=+8I+<-_qvu(+=R!9@(msQdIZ$sb^{745C)<6G`B ztmi4EpeOj;zC>F}w;nWP=ZY_e}@fP0GgK{YO8WQ-OI} zk@jtO&gzU^o&1`a^GT%G8d8VJ*F`e_cKE<#;8)iKCRPQ36v(uK${Hyzu;yjHkReDajPG+b_NKxFJ=w9I zW2;LH_K^IYC*ln|duO}ra4%e=q`;QI7Id(xTda}=($K^4R%TgZPG(4=64Ki9mX@P+ zeVGwLGrjz7ViVf~T}7Cu4=e!rl$Y7XrIm? zv4f>1%rF2+0u3oMvPMQmrsX7}Oz(U9Rz!Rae~$Spv1_qW8151jDgJ7_$U^{^5RS7Xkdk1m2g98`{cLdu39l)Xv;*NIz E0>z+rSpWb4 literal 0 HcmV?d00001 diff --git a/src/Examples/EF6/Ex5_Store/EFModelFirstDemo-master/.gitattributes b/src/Examples/EF6/Ex5_Store/EFModelFirstDemo-master/.gitattributes new file mode 100644 index 000000000..1ff0c4230 --- /dev/null +++ b/src/Examples/EF6/Ex5_Store/EFModelFirstDemo-master/.gitattributes @@ -0,0 +1,63 @@ +############################################################################### +# Set default behavior to automatically normalize line endings. +############################################################################### +* text=auto + +############################################################################### +# Set default behavior for command prompt diff. +# +# This is need for earlier builds of msysgit that does not have it on by +# default for csharp files. +# Note: This is only used by command line +############################################################################### +#*.cs diff=csharp + +############################################################################### +# Set the merge driver for project and solution files +# +# Merging from the command prompt will add diff markers to the files if there +# are conflicts (Merging from VS is not affected by the settings below, in VS +# the diff markers are never inserted). Diff markers may cause the following +# file extensions to fail to load in VS. An alternative would be to treat +# these files as binary and thus will always conflict and require user +# intervention with every merge. To do so, just uncomment the entries below +############################################################################### +#*.sln merge=binary +#*.csproj merge=binary +#*.vbproj merge=binary +#*.vcxproj merge=binary +#*.vcproj merge=binary +#*.dbproj merge=binary +#*.fsproj merge=binary +#*.lsproj merge=binary +#*.wixproj merge=binary +#*.modelproj merge=binary +#*.sqlproj merge=binary +#*.wwaproj merge=binary + +############################################################################### +# behavior for image files +# +# image files are treated as binary by default. +############################################################################### +#*.jpg binary +#*.png binary +#*.gif binary + +############################################################################### +# diff behavior for common document formats +# +# Convert binary document formats to text before diffing them. This feature +# is only available from the command line. Turn it on by uncommenting the +# entries below. +############################################################################### +#*.doc diff=astextplain +#*.DOC diff=astextplain +#*.docx diff=astextplain +#*.DOCX diff=astextplain +#*.dot diff=astextplain +#*.DOT diff=astextplain +#*.pdf diff=astextplain +#*.PDF diff=astextplain +#*.rtf diff=astextplain +#*.RTF diff=astextplain diff --git a/src/Examples/EF6/Ex5_Store/EFModelFirstDemo-master/.gitignore b/src/Examples/EF6/Ex5_Store/EFModelFirstDemo-master/.gitignore new file mode 100644 index 000000000..3c4efe206 --- /dev/null +++ b/src/Examples/EF6/Ex5_Store/EFModelFirstDemo-master/.gitignore @@ -0,0 +1,261 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. + +# User-specific files +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ + +# Visual Studio 2015 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUNIT +*.VisualState.xml +TestResult.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# DNX +project.lock.json +project.fragment.lock.json +artifacts/ + +*_i.c +*_p.c +*_i.h +*.ilk +*.meta +*.obj +*.pch +*.pdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# JustCode is a .NET coding add-in +.JustCode + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# TODO: Comment the next line if you want to checkin your web deploy settings +# but database connection strings (with potential passwords) will be unencrypted +#*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# The packages folder can be ignored because of Package Restore +**/packages/* +# except build/, which is used as an MSBuild target. +!**/packages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/packages/repositories.config +# NuGet v3's project.json files produces more ignoreable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +node_modules/ +orleans.codegen.cs + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm + +# SQL Server files +*.mdf +*.ldf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# JetBrains Rider +.idea/ +*.sln.iml + +# CodeRush +.cr/ + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc \ No newline at end of file diff --git a/src/Examples/EF6/Ex5_Store/EFModelFirstDemo-master/EFModelFirstDemo.sln b/src/Examples/EF6/Ex5_Store/EFModelFirstDemo-master/EFModelFirstDemo.sln new file mode 100644 index 000000000..582df4928 --- /dev/null +++ b/src/Examples/EF6/Ex5_Store/EFModelFirstDemo-master/EFModelFirstDemo.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.27703.2026 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EFModelFirstDemo", "EFModelFirstDemo\EFModelFirstDemo.csproj", "{E617D310-1925-41E4-AAC3-A23C78B7D420}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {E617D310-1925-41E4-AAC3-A23C78B7D420}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {E617D310-1925-41E4-AAC3-A23C78B7D420}.Debug|Any CPU.Build.0 = Debug|Any CPU + {E617D310-1925-41E4-AAC3-A23C78B7D420}.Release|Any CPU.ActiveCfg = Release|Any CPU + {E617D310-1925-41E4-AAC3-A23C78B7D420}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {75BAC12B-7AA9-4B27-BCC5-9420642C165E} + EndGlobalSection +EndGlobal diff --git a/src/Examples/EF6/Ex5_Store/EFModelFirstDemo-master/EFModelFirstDemo/App.config b/src/Examples/EF6/Ex5_Store/EFModelFirstDemo-master/EFModelFirstDemo/App.config new file mode 100644 index 000000000..52e2f9a24 --- /dev/null +++ b/src/Examples/EF6/Ex5_Store/EFModelFirstDemo-master/EFModelFirstDemo/App.config @@ -0,0 +1,23 @@ + + + + +

+ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/Examples/EF6/Ex5_Store/EFModelFirstDemo-master/EFModelFirstDemo/Course.cs b/src/Examples/EF6/Ex5_Store/EFModelFirstDemo-master/EFModelFirstDemo/Course.cs new file mode 100644 index 000000000..15ab09ba5 --- /dev/null +++ b/src/Examples/EF6/Ex5_Store/EFModelFirstDemo-master/EFModelFirstDemo/Course.cs @@ -0,0 +1,30 @@ +//------------------------------------------------------------------------------ +// +// This code was generated from a template. +// +// Manual changes to this file may cause unexpected behavior in your application. +// Manual changes to this file will be overwritten if the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace EFModelFirstDemo +{ + using System; + using System.Collections.Generic; + + public partial class Course + { + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] + public Course() + { + this.Enrollements = new HashSet(); + } + + public int CourseId { get; set; } + public string Title { get; set; } + public string Credits { get; set; } + + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] + public virtual ICollection Enrollements { get; set; } + } +} diff --git a/src/Examples/EF6/Ex5_Store/EFModelFirstDemo-master/EFModelFirstDemo/EFModelFirstDemo.csproj b/src/Examples/EF6/Ex5_Store/EFModelFirstDemo-master/EFModelFirstDemo/EFModelFirstDemo.csproj new file mode 100644 index 000000000..dc169fe16 --- /dev/null +++ b/src/Examples/EF6/Ex5_Store/EFModelFirstDemo-master/EFModelFirstDemo/EFModelFirstDemo.csproj @@ -0,0 +1,109 @@ + + + + + Debug + AnyCPU + {E617D310-1925-41E4-AAC3-A23C78B7D420} + Exe + EFModelFirstDemo + EFModelFirstDemo + v4.6.1 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + ..\packages\EntityFramework.6.2.0\lib\net45\EntityFramework.dll + + + ..\packages\EntityFramework.6.2.0\lib\net45\EntityFramework.SqlServer.dll + + + + + + + + + + + + + + + + ModelFirstDemoDB.tt + + + ModelFirstDemoDB.tt + + + True + True + ModelFirstDemoDB.Context.tt + + + True + True + ModelFirstDemoDB.tt + + + True + True + ModelFirstDemoDB.edmx + + + + + ModelFirstDemoDB.tt + + + + + + EntityModelCodeGenerator + ModelFirstDemoDB.Designer.cs + + + ModelFirstDemoDB.edmx + + + + + + TextTemplatingFileGenerator + ModelFirstDemoDB.Context.cs + ModelFirstDemoDB.edmx + + + + TextTemplatingFileGenerator + ModelFirstDemoDB.cs + ModelFirstDemoDB.edmx + + + + + + + \ No newline at end of file diff --git a/src/Examples/EF6/Ex5_Store/EFModelFirstDemo-master/EFModelFirstDemo/Enrollement.cs b/src/Examples/EF6/Ex5_Store/EFModelFirstDemo-master/EFModelFirstDemo/Enrollement.cs new file mode 100644 index 000000000..53babb9f7 --- /dev/null +++ b/src/Examples/EF6/Ex5_Store/EFModelFirstDemo-master/EFModelFirstDemo/Enrollement.cs @@ -0,0 +1,27 @@ +//------------------------------------------------------------------------------ +// +// This code was generated from a template. +// +// Manual changes to this file may cause unexpected behavior in your application. +// Manual changes to this file will be overwritten if the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace EFModelFirstDemo +{ + using System; + using System.Collections.Generic; + + public partial class Enrollement + { + public int EnrollementId { get; set; } + public int CourseId { get; set; } + public int StudentId { get; set; } + public int Grade { get; set; } + public int StudentStudentId { get; set; } + public int CourseCourseId { get; set; } + + public virtual Student Student { get; set; } + public virtual Course Course { get; set; } + } +} diff --git a/src/Examples/EF6/Ex5_Store/EFModelFirstDemo-master/EFModelFirstDemo/ModelFirstDemoDB.Context.cs b/src/Examples/EF6/Ex5_Store/EFModelFirstDemo-master/EFModelFirstDemo/ModelFirstDemoDB.Context.cs new file mode 100644 index 000000000..c5aa5843a --- /dev/null +++ b/src/Examples/EF6/Ex5_Store/EFModelFirstDemo-master/EFModelFirstDemo/ModelFirstDemoDB.Context.cs @@ -0,0 +1,32 @@ +//------------------------------------------------------------------------------ +// +// This code was generated from a template. +// +// Manual changes to this file may cause unexpected behavior in your application. +// Manual changes to this file will be overwritten if the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace EFModelFirstDemo +{ + using System; + using System.Data.Entity; + using System.Data.Entity.Infrastructure; + + public partial class ModelFirstDemoDBContext : DbContext + { + public ModelFirstDemoDBContext() + : base("name=ModelFirstDemoDBContext") + { + } + + protected override void OnModelCreating(DbModelBuilder modelBuilder) + { + throw new UnintentionalCodeFirstException(); + } + + public virtual DbSet Students { get; set; } + public virtual DbSet Enrollements { get; set; } + public virtual DbSet Courses { get; set; } + } +} diff --git a/src/Examples/EF6/Ex5_Store/EFModelFirstDemo-master/EFModelFirstDemo/ModelFirstDemoDB.Context.tt b/src/Examples/EF6/Ex5_Store/EFModelFirstDemo-master/EFModelFirstDemo/ModelFirstDemoDB.Context.tt new file mode 100644 index 000000000..f5e638991 --- /dev/null +++ b/src/Examples/EF6/Ex5_Store/EFModelFirstDemo-master/EFModelFirstDemo/ModelFirstDemoDB.Context.tt @@ -0,0 +1,636 @@ +<#@ template language="C#" debug="false" hostspecific="true"#> +<#@ include file="EF6.Utility.CS.ttinclude"#><#@ + output extension=".cs"#><# + +const string inputFile = @"ModelFirstDemoDB.edmx"; +var textTransform = DynamicTextTransformation.Create(this); +var code = new CodeGenerationTools(this); +var ef = new MetadataTools(this); +var typeMapper = new TypeMapper(code, ef, textTransform.Errors); +var loader = new EdmMetadataLoader(textTransform.Host, textTransform.Errors); +var itemCollection = loader.CreateEdmItemCollection(inputFile); +var modelNamespace = loader.GetModelNamespace(inputFile); +var codeStringGenerator = new CodeStringGenerator(code, typeMapper, ef); + +var container = itemCollection.OfType().FirstOrDefault(); +if (container == null) +{ + return string.Empty; +} +#> +//------------------------------------------------------------------------------ +// +// <#=CodeGenerationTools.GetResourceString("Template_GeneratedCodeCommentLine1")#> +// +// <#=CodeGenerationTools.GetResourceString("Template_GeneratedCodeCommentLine2")#> +// <#=CodeGenerationTools.GetResourceString("Template_GeneratedCodeCommentLine3")#> +// +//------------------------------------------------------------------------------ + +<# + +var codeNamespace = code.VsNamespaceSuggestion(); +if (!String.IsNullOrEmpty(codeNamespace)) +{ +#> +namespace <#=code.EscapeNamespace(codeNamespace)#> +{ +<# + PushIndent(" "); +} + +#> +using System; +using System.Data.Entity; +using System.Data.Entity.Infrastructure; +<# +if (container.FunctionImports.Any()) +{ +#> +using System.Data.Entity.Core.Objects; +using System.Linq; +<# +} +#> + +<#=Accessibility.ForType(container)#> partial class <#=code.Escape(container)#> : DbContext +{ + public <#=code.Escape(container)#>() + : base("name=<#=container.Name#>") + { +<# +if (!loader.IsLazyLoadingEnabled(container)) +{ +#> + this.Configuration.LazyLoadingEnabled = false; +<# +} + +foreach (var entitySet in container.BaseEntitySets.OfType()) +{ + // Note: the DbSet members are defined below such that the getter and + // setter always have the same accessibility as the DbSet definition + if (Accessibility.ForReadOnlyProperty(entitySet) != "public") + { +#> + <#=codeStringGenerator.DbSetInitializer(entitySet)#> +<# + } +} +#> + } + + protected override void OnModelCreating(DbModelBuilder modelBuilder) + { + throw new UnintentionalCodeFirstException(); + } + +<# + foreach (var entitySet in container.BaseEntitySets.OfType()) + { +#> + <#=codeStringGenerator.DbSet(entitySet)#> +<# + } + + foreach (var edmFunction in container.FunctionImports) + { + WriteFunctionImport(typeMapper, codeStringGenerator, edmFunction, modelNamespace, includeMergeOption: false); + } +#> +} +<# + +if (!String.IsNullOrEmpty(codeNamespace)) +{ + PopIndent(); +#> +} +<# +} +#> +<#+ + +private void WriteFunctionImport(TypeMapper typeMapper, CodeStringGenerator codeStringGenerator, EdmFunction edmFunction, string modelNamespace, bool includeMergeOption) +{ + if (typeMapper.IsComposable(edmFunction)) + { +#> + + [DbFunction("<#=edmFunction.NamespaceName#>", "<#=edmFunction.Name#>")] + <#=codeStringGenerator.ComposableFunctionMethod(edmFunction, modelNamespace)#> + { +<#+ + codeStringGenerator.WriteFunctionParameters(edmFunction, WriteFunctionParameter); +#> + <#=codeStringGenerator.ComposableCreateQuery(edmFunction, modelNamespace)#> + } +<#+ + } + else + { +#> + + <#=codeStringGenerator.FunctionMethod(edmFunction, modelNamespace, includeMergeOption)#> + { +<#+ + codeStringGenerator.WriteFunctionParameters(edmFunction, WriteFunctionParameter); +#> + <#=codeStringGenerator.ExecuteFunction(edmFunction, modelNamespace, includeMergeOption)#> + } +<#+ + if (typeMapper.GenerateMergeOptionFunction(edmFunction, includeMergeOption)) + { + WriteFunctionImport(typeMapper, codeStringGenerator, edmFunction, modelNamespace, includeMergeOption: true); + } + } +} + +public void WriteFunctionParameter(string name, string isNotNull, string notNullInit, string nullInit) +{ +#> + var <#=name#> = <#=isNotNull#> ? + <#=notNullInit#> : + <#=nullInit#>; + +<#+ +} + +public const string TemplateId = "CSharp_DbContext_Context_EF6"; + +public class CodeStringGenerator +{ + private readonly CodeGenerationTools _code; + private readonly TypeMapper _typeMapper; + private readonly MetadataTools _ef; + + public CodeStringGenerator(CodeGenerationTools code, TypeMapper typeMapper, MetadataTools ef) + { + ArgumentNotNull(code, "code"); + ArgumentNotNull(typeMapper, "typeMapper"); + ArgumentNotNull(ef, "ef"); + + _code = code; + _typeMapper = typeMapper; + _ef = ef; + } + + public string Property(EdmProperty edmProperty) + { + return string.Format( + CultureInfo.InvariantCulture, + "{0} {1} {2} {{ {3}get; {4}set; }}", + Accessibility.ForProperty(edmProperty), + _typeMapper.GetTypeName(edmProperty.TypeUsage), + _code.Escape(edmProperty), + _code.SpaceAfter(Accessibility.ForGetter(edmProperty)), + _code.SpaceAfter(Accessibility.ForSetter(edmProperty))); + } + + public string NavigationProperty(NavigationProperty navProp) + { + var endType = _typeMapper.GetTypeName(navProp.ToEndMember.GetEntityType()); + return string.Format( + CultureInfo.InvariantCulture, + "{0} {1} {2} {{ {3}get; {4}set; }}", + AccessibilityAndVirtual(Accessibility.ForNavigationProperty(navProp)), + navProp.ToEndMember.RelationshipMultiplicity == RelationshipMultiplicity.Many ? ("ICollection<" + endType + ">") : endType, + _code.Escape(navProp), + _code.SpaceAfter(Accessibility.ForGetter(navProp)), + _code.SpaceAfter(Accessibility.ForSetter(navProp))); + } + + public string AccessibilityAndVirtual(string accessibility) + { + return accessibility + (accessibility != "private" ? " virtual" : ""); + } + + public string EntityClassOpening(EntityType entity) + { + return string.Format( + CultureInfo.InvariantCulture, + "{0} {1}partial class {2}{3}", + Accessibility.ForType(entity), + _code.SpaceAfter(_code.AbstractOption(entity)), + _code.Escape(entity), + _code.StringBefore(" : ", _typeMapper.GetTypeName(entity.BaseType))); + } + + public string EnumOpening(SimpleType enumType) + { + return string.Format( + CultureInfo.InvariantCulture, + "{0} enum {1} : {2}", + Accessibility.ForType(enumType), + _code.Escape(enumType), + _code.Escape(_typeMapper.UnderlyingClrType(enumType))); + } + + public void WriteFunctionParameters(EdmFunction edmFunction, Action writeParameter) + { + var parameters = FunctionImportParameter.Create(edmFunction.Parameters, _code, _ef); + foreach (var parameter in parameters.Where(p => p.NeedsLocalVariable)) + { + var isNotNull = parameter.IsNullableOfT ? parameter.FunctionParameterName + ".HasValue" : parameter.FunctionParameterName + " != null"; + var notNullInit = "new ObjectParameter(\"" + parameter.EsqlParameterName + "\", " + parameter.FunctionParameterName + ")"; + var nullInit = "new ObjectParameter(\"" + parameter.EsqlParameterName + "\", typeof(" + TypeMapper.FixNamespaces(parameter.RawClrTypeName) + "))"; + writeParameter(parameter.LocalVariableName, isNotNull, notNullInit, nullInit); + } + } + + public string ComposableFunctionMethod(EdmFunction edmFunction, string modelNamespace) + { + var parameters = _typeMapper.GetParameters(edmFunction); + + return string.Format( + CultureInfo.InvariantCulture, + "{0} IQueryable<{1}> {2}({3})", + AccessibilityAndVirtual(Accessibility.ForMethod(edmFunction)), + _typeMapper.GetTypeName(_typeMapper.GetReturnType(edmFunction), modelNamespace), + _code.Escape(edmFunction), + string.Join(", ", parameters.Select(p => TypeMapper.FixNamespaces(p.FunctionParameterType) + " " + p.FunctionParameterName).ToArray())); + } + + public string ComposableCreateQuery(EdmFunction edmFunction, string modelNamespace) + { + var parameters = _typeMapper.GetParameters(edmFunction); + + return string.Format( + CultureInfo.InvariantCulture, + "return ((IObjectContextAdapter)this).ObjectContext.CreateQuery<{0}>(\"[{1}].[{2}]({3})\"{4});", + _typeMapper.GetTypeName(_typeMapper.GetReturnType(edmFunction), modelNamespace), + edmFunction.NamespaceName, + edmFunction.Name, + string.Join(", ", parameters.Select(p => "@" + p.EsqlParameterName).ToArray()), + _code.StringBefore(", ", string.Join(", ", parameters.Select(p => p.ExecuteParameterName).ToArray()))); + } + + public string FunctionMethod(EdmFunction edmFunction, string modelNamespace, bool includeMergeOption) + { + var parameters = _typeMapper.GetParameters(edmFunction); + var returnType = _typeMapper.GetReturnType(edmFunction); + + var paramList = String.Join(", ", parameters.Select(p => TypeMapper.FixNamespaces(p.FunctionParameterType) + " " + p.FunctionParameterName).ToArray()); + if (includeMergeOption) + { + paramList = _code.StringAfter(paramList, ", ") + "MergeOption mergeOption"; + } + + return string.Format( + CultureInfo.InvariantCulture, + "{0} {1} {2}({3})", + AccessibilityAndVirtual(Accessibility.ForMethod(edmFunction)), + returnType == null ? "int" : "ObjectResult<" + _typeMapper.GetTypeName(returnType, modelNamespace) + ">", + _code.Escape(edmFunction), + paramList); + } + + public string ExecuteFunction(EdmFunction edmFunction, string modelNamespace, bool includeMergeOption) + { + var parameters = _typeMapper.GetParameters(edmFunction); + var returnType = _typeMapper.GetReturnType(edmFunction); + + var callParams = _code.StringBefore(", ", String.Join(", ", parameters.Select(p => p.ExecuteParameterName).ToArray())); + if (includeMergeOption) + { + callParams = ", mergeOption" + callParams; + } + + return string.Format( + CultureInfo.InvariantCulture, + "return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction{0}(\"{1}\"{2});", + returnType == null ? "" : "<" + _typeMapper.GetTypeName(returnType, modelNamespace) + ">", + edmFunction.Name, + callParams); + } + + public string DbSet(EntitySet entitySet) + { + return string.Format( + CultureInfo.InvariantCulture, + "{0} virtual DbSet<{1}> {2} {{ get; set; }}", + Accessibility.ForReadOnlyProperty(entitySet), + _typeMapper.GetTypeName(entitySet.ElementType), + _code.Escape(entitySet)); + } + + public string DbSetInitializer(EntitySet entitySet) + { + return string.Format( + CultureInfo.InvariantCulture, + "{0} = Set<{1}>();", + _code.Escape(entitySet), + _typeMapper.GetTypeName(entitySet.ElementType)); + } + + public string UsingDirectives(bool inHeader, bool includeCollections = true) + { + return inHeader == string.IsNullOrEmpty(_code.VsNamespaceSuggestion()) + ? string.Format( + CultureInfo.InvariantCulture, + "{0}using System;{1}" + + "{2}", + inHeader ? Environment.NewLine : "", + includeCollections ? (Environment.NewLine + "using System.Collections.Generic;") : "", + inHeader ? "" : Environment.NewLine) + : ""; + } +} + +public class TypeMapper +{ + private const string ExternalTypeNameAttributeName = @"http://schemas.microsoft.com/ado/2006/04/codegeneration:ExternalTypeName"; + + private readonly System.Collections.IList _errors; + private readonly CodeGenerationTools _code; + private readonly MetadataTools _ef; + + public static string FixNamespaces(string typeName) + { + return typeName.Replace("System.Data.Spatial.", "System.Data.Entity.Spatial."); + } + + public TypeMapper(CodeGenerationTools code, MetadataTools ef, System.Collections.IList errors) + { + ArgumentNotNull(code, "code"); + ArgumentNotNull(ef, "ef"); + ArgumentNotNull(errors, "errors"); + + _code = code; + _ef = ef; + _errors = errors; + } + + public string GetTypeName(TypeUsage typeUsage) + { + return typeUsage == null ? null : GetTypeName(typeUsage.EdmType, _ef.IsNullable(typeUsage), modelNamespace: null); + } + + public string GetTypeName(EdmType edmType) + { + return GetTypeName(edmType, isNullable: null, modelNamespace: null); + } + + public string GetTypeName(TypeUsage typeUsage, string modelNamespace) + { + return typeUsage == null ? null : GetTypeName(typeUsage.EdmType, _ef.IsNullable(typeUsage), modelNamespace); + } + + public string GetTypeName(EdmType edmType, string modelNamespace) + { + return GetTypeName(edmType, isNullable: null, modelNamespace: modelNamespace); + } + + public string GetTypeName(EdmType edmType, bool? isNullable, string modelNamespace) + { + if (edmType == null) + { + return null; + } + + var collectionType = edmType as CollectionType; + if (collectionType != null) + { + return String.Format(CultureInfo.InvariantCulture, "ICollection<{0}>", GetTypeName(collectionType.TypeUsage, modelNamespace)); + } + + var typeName = _code.Escape(edmType.MetadataProperties + .Where(p => p.Name == ExternalTypeNameAttributeName) + .Select(p => (string)p.Value) + .FirstOrDefault()) + ?? (modelNamespace != null && edmType.NamespaceName != modelNamespace ? + _code.CreateFullName(_code.EscapeNamespace(edmType.NamespaceName), _code.Escape(edmType)) : + _code.Escape(edmType)); + + if (edmType is StructuralType) + { + return typeName; + } + + if (edmType is SimpleType) + { + var clrType = UnderlyingClrType(edmType); + if (!IsEnumType(edmType)) + { + typeName = _code.Escape(clrType); + } + + typeName = FixNamespaces(typeName); + + return clrType.IsValueType && isNullable == true ? + String.Format(CultureInfo.InvariantCulture, "Nullable<{0}>", typeName) : + typeName; + } + + throw new ArgumentException("edmType"); + } + + public Type UnderlyingClrType(EdmType edmType) + { + ArgumentNotNull(edmType, "edmType"); + + var primitiveType = edmType as PrimitiveType; + if (primitiveType != null) + { + return primitiveType.ClrEquivalentType; + } + + if (IsEnumType(edmType)) + { + return GetEnumUnderlyingType(edmType).ClrEquivalentType; + } + + return typeof(object); + } + + public object GetEnumMemberValue(MetadataItem enumMember) + { + ArgumentNotNull(enumMember, "enumMember"); + + var valueProperty = enumMember.GetType().GetProperty("Value"); + return valueProperty == null ? null : valueProperty.GetValue(enumMember, null); + } + + public string GetEnumMemberName(MetadataItem enumMember) + { + ArgumentNotNull(enumMember, "enumMember"); + + var nameProperty = enumMember.GetType().GetProperty("Name"); + return nameProperty == null ? null : (string)nameProperty.GetValue(enumMember, null); + } + + public System.Collections.IEnumerable GetEnumMembers(EdmType enumType) + { + ArgumentNotNull(enumType, "enumType"); + + var membersProperty = enumType.GetType().GetProperty("Members"); + return membersProperty != null + ? (System.Collections.IEnumerable)membersProperty.GetValue(enumType, null) + : Enumerable.Empty(); + } + + public bool EnumIsFlags(EdmType enumType) + { + ArgumentNotNull(enumType, "enumType"); + + var isFlagsProperty = enumType.GetType().GetProperty("IsFlags"); + return isFlagsProperty != null && (bool)isFlagsProperty.GetValue(enumType, null); + } + + public bool IsEnumType(GlobalItem edmType) + { + ArgumentNotNull(edmType, "edmType"); + + return edmType.GetType().Name == "EnumType"; + } + + public PrimitiveType GetEnumUnderlyingType(EdmType enumType) + { + ArgumentNotNull(enumType, "enumType"); + + return (PrimitiveType)enumType.GetType().GetProperty("UnderlyingType").GetValue(enumType, null); + } + + public string CreateLiteral(object value) + { + if (value == null || value.GetType() != typeof(TimeSpan)) + { + return _code.CreateLiteral(value); + } + + return string.Format(CultureInfo.InvariantCulture, "new TimeSpan({0})", ((TimeSpan)value).Ticks); + } + + public bool VerifyCaseInsensitiveTypeUniqueness(IEnumerable types, string sourceFile) + { + ArgumentNotNull(types, "types"); + ArgumentNotNull(sourceFile, "sourceFile"); + + var hash = new HashSet(StringComparer.InvariantCultureIgnoreCase); + if (types.Any(item => !hash.Add(item))) + { + _errors.Add( + new CompilerError(sourceFile, -1, -1, "6023", + String.Format(CultureInfo.CurrentCulture, CodeGenerationTools.GetResourceString("Template_CaseInsensitiveTypeConflict")))); + return false; + } + return true; + } + + public IEnumerable GetEnumItemsToGenerate(IEnumerable itemCollection) + { + return GetItemsToGenerate(itemCollection) + .Where(e => IsEnumType(e)); + } + + public IEnumerable GetItemsToGenerate(IEnumerable itemCollection) where T: EdmType + { + return itemCollection + .OfType() + .Where(i => !i.MetadataProperties.Any(p => p.Name == ExternalTypeNameAttributeName)) + .OrderBy(i => i.Name); + } + + public IEnumerable GetAllGlobalItems(IEnumerable itemCollection) + { + return itemCollection + .Where(i => i is EntityType || i is ComplexType || i is EntityContainer || IsEnumType(i)) + .Select(g => GetGlobalItemName(g)); + } + + public string GetGlobalItemName(GlobalItem item) + { + if (item is EdmType) + { + return ((EdmType)item).Name; + } + else + { + return ((EntityContainer)item).Name; + } + } + + public IEnumerable GetSimpleProperties(EntityType type) + { + return type.Properties.Where(p => p.TypeUsage.EdmType is SimpleType && p.DeclaringType == type); + } + + public IEnumerable GetSimpleProperties(ComplexType type) + { + return type.Properties.Where(p => p.TypeUsage.EdmType is SimpleType && p.DeclaringType == type); + } + + public IEnumerable GetComplexProperties(EntityType type) + { + return type.Properties.Where(p => p.TypeUsage.EdmType is ComplexType && p.DeclaringType == type); + } + + public IEnumerable GetComplexProperties(ComplexType type) + { + return type.Properties.Where(p => p.TypeUsage.EdmType is ComplexType && p.DeclaringType == type); + } + + public IEnumerable GetPropertiesWithDefaultValues(EntityType type) + { + return type.Properties.Where(p => p.TypeUsage.EdmType is SimpleType && p.DeclaringType == type && p.DefaultValue != null); + } + + public IEnumerable GetPropertiesWithDefaultValues(ComplexType type) + { + return type.Properties.Where(p => p.TypeUsage.EdmType is SimpleType && p.DeclaringType == type && p.DefaultValue != null); + } + + public IEnumerable GetNavigationProperties(EntityType type) + { + return type.NavigationProperties.Where(np => np.DeclaringType == type); + } + + public IEnumerable GetCollectionNavigationProperties(EntityType type) + { + return type.NavigationProperties.Where(np => np.DeclaringType == type && np.ToEndMember.RelationshipMultiplicity == RelationshipMultiplicity.Many); + } + + public FunctionParameter GetReturnParameter(EdmFunction edmFunction) + { + ArgumentNotNull(edmFunction, "edmFunction"); + + var returnParamsProperty = edmFunction.GetType().GetProperty("ReturnParameters"); + return returnParamsProperty == null + ? edmFunction.ReturnParameter + : ((IEnumerable)returnParamsProperty.GetValue(edmFunction, null)).FirstOrDefault(); + } + + public bool IsComposable(EdmFunction edmFunction) + { + ArgumentNotNull(edmFunction, "edmFunction"); + + var isComposableProperty = edmFunction.GetType().GetProperty("IsComposableAttribute"); + return isComposableProperty != null && (bool)isComposableProperty.GetValue(edmFunction, null); + } + + public IEnumerable GetParameters(EdmFunction edmFunction) + { + return FunctionImportParameter.Create(edmFunction.Parameters, _code, _ef); + } + + public TypeUsage GetReturnType(EdmFunction edmFunction) + { + var returnParam = GetReturnParameter(edmFunction); + return returnParam == null ? null : _ef.GetElementType(returnParam.TypeUsage); + } + + public bool GenerateMergeOptionFunction(EdmFunction edmFunction, bool includeMergeOption) + { + var returnType = GetReturnType(edmFunction); + return !includeMergeOption && returnType != null && returnType.EdmType.BuiltInTypeKind == BuiltInTypeKind.EntityType; + } +} + +public static void ArgumentNotNull(T arg, string name) where T : class +{ + if (arg == null) + { + throw new ArgumentNullException(name); + } +} +#> \ No newline at end of file diff --git a/src/Examples/EF6/Ex5_Store/EFModelFirstDemo-master/EFModelFirstDemo/ModelFirstDemoDB.Designer.cs b/src/Examples/EF6/Ex5_Store/EFModelFirstDemo-master/EFModelFirstDemo/ModelFirstDemoDB.Designer.cs new file mode 100644 index 000000000..648cb9a16 --- /dev/null +++ b/src/Examples/EF6/Ex5_Store/EFModelFirstDemo-master/EFModelFirstDemo/ModelFirstDemoDB.Designer.cs @@ -0,0 +1,10 @@ +// T4 code generation is enabled for model 'c:\users\dell\source\repos\EFModelFirstDemo\EFModelFirstDemo\ModelFirstDemoDB.edmx'. +// To enable legacy code generation, change the value of the 'Code Generation Strategy' designer +// property to 'Legacy ObjectContext'. This property is available in the Properties Window when the model +// is open in the designer. + +// If no context and entity classes have been generated, it may be because you created an empty model but +// have not yet chosen which version of Entity Framework to use. To generate a context class and entity +// classes for your model, open the model in the designer, right-click on the designer surface, and +// select 'Update Model from Database...', 'Generate Database from Model...', or 'Add Code Generation +// Item...'. \ No newline at end of file diff --git a/src/Examples/EF6/Ex5_Store/EFModelFirstDemo-master/EFModelFirstDemo/ModelFirstDemoDB.cs b/src/Examples/EF6/Ex5_Store/EFModelFirstDemo-master/EFModelFirstDemo/ModelFirstDemoDB.cs new file mode 100644 index 000000000..7cc066228 --- /dev/null +++ b/src/Examples/EF6/Ex5_Store/EFModelFirstDemo-master/EFModelFirstDemo/ModelFirstDemoDB.cs @@ -0,0 +1,9 @@ +//------------------------------------------------------------------------------ +// +// This code was generated from a template. +// +// Manual changes to this file may cause unexpected behavior in your application. +// Manual changes to this file will be overwritten if the code is regenerated. +// +//------------------------------------------------------------------------------ + diff --git a/src/Examples/EF6/Ex5_Store/EFModelFirstDemo-master/EFModelFirstDemo/ModelFirstDemoDB.edmx b/src/Examples/EF6/Ex5_Store/EFModelFirstDemo-master/EFModelFirstDemo/ModelFirstDemoDB.edmx new file mode 100644 index 000000000..6f9373349 --- /dev/null +++ b/src/Examples/EF6/Ex5_Store/EFModelFirstDemo-master/EFModelFirstDemo/ModelFirstDemoDB.edmx @@ -0,0 +1,205 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/Examples/EF6/Ex5_Store/EFModelFirstDemo-master/EFModelFirstDemo/ModelFirstDemoDB.edmx.diagram b/src/Examples/EF6/Ex5_Store/EFModelFirstDemo-master/EFModelFirstDemo/ModelFirstDemoDB.edmx.diagram new file mode 100644 index 000000000..32a2981ff --- /dev/null +++ b/src/Examples/EF6/Ex5_Store/EFModelFirstDemo-master/EFModelFirstDemo/ModelFirstDemoDB.edmx.diagram @@ -0,0 +1,16 @@ + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/Examples/EF6/Ex5_Store/EFModelFirstDemo-master/EFModelFirstDemo/ModelFirstDemoDB.edmx.sql b/src/Examples/EF6/Ex5_Store/EFModelFirstDemo-master/EFModelFirstDemo/ModelFirstDemoDB.edmx.sql new file mode 100644 index 000000000..11dd78349 --- /dev/null +++ b/src/Examples/EF6/Ex5_Store/EFModelFirstDemo-master/EFModelFirstDemo/ModelFirstDemoDB.edmx.sql @@ -0,0 +1,116 @@ + +-- -------------------------------------------------- +-- Entity Designer DDL Script for SQL Server 2005, 2008, 2012 and Azure +-- -------------------------------------------------- +-- Date Created: 08/09/2018 21:11:22 +-- Generated from EDMX file: c:\users\dell\source\repos\EFModelFirstDemo\EFModelFirstDemo\ModelFirstDemoDB.edmx +-- -------------------------------------------------- + +SET QUOTED_IDENTIFIER OFF; +GO +USE [ModelFirstDemoDB]; +GO +IF SCHEMA_ID(N'dbo') IS NULL EXECUTE(N'CREATE SCHEMA [dbo]'); +GO + +-- -------------------------------------------------- +-- Dropping existing FOREIGN KEY constraints +-- -------------------------------------------------- + + +-- -------------------------------------------------- +-- Dropping existing tables +-- -------------------------------------------------- + + +-- -------------------------------------------------- +-- Creating all tables +-- -------------------------------------------------- + +-- Creating table 'Students' +CREATE TABLE [dbo].[Students] ( + [StudentId] int IDENTITY(1,1) NOT NULL, + [FirstName] nvarchar(max) NOT NULL, + [LastName] nvarchar(max) NOT NULL, + [EnrollementDate] datetime NOT NULL +); +GO + +-- Creating table 'Enrollements' +CREATE TABLE [dbo].[Enrollements] ( + [EnrollementId] int IDENTITY(1,1) NOT NULL, + [CourseId] int NOT NULL, + [StudentId] int NOT NULL, + [Grade] int NOT NULL, + [StudentStudentId] int NOT NULL, + [CourseCourseId] int NOT NULL +); +GO + +-- Creating table 'Courses' +CREATE TABLE [dbo].[Courses] ( + [CourseId] int IDENTITY(1,1) NOT NULL, + [Title] nvarchar(max) NOT NULL, + [Credits] nvarchar(max) NOT NULL +); +GO + +-- -------------------------------------------------- +-- Creating all PRIMARY KEY constraints +-- -------------------------------------------------- + +-- Creating primary key on [StudentId] in table 'Students' +ALTER TABLE [dbo].[Students] +ADD CONSTRAINT [PK_Students] + PRIMARY KEY CLUSTERED ([StudentId] ASC); +GO + +-- Creating primary key on [EnrollementId] in table 'Enrollements' +ALTER TABLE [dbo].[Enrollements] +ADD CONSTRAINT [PK_Enrollements] + PRIMARY KEY CLUSTERED ([EnrollementId] ASC); +GO + +-- Creating primary key on [CourseId] in table 'Courses' +ALTER TABLE [dbo].[Courses] +ADD CONSTRAINT [PK_Courses] + PRIMARY KEY CLUSTERED ([CourseId] ASC); +GO + +-- -------------------------------------------------- +-- Creating all FOREIGN KEY constraints +-- -------------------------------------------------- + +-- Creating foreign key on [StudentStudentId] in table 'Enrollements' +ALTER TABLE [dbo].[Enrollements] +ADD CONSTRAINT [FK_StudentEnrollement] + FOREIGN KEY ([StudentStudentId]) + REFERENCES [dbo].[Students] + ([StudentId]) + ON DELETE NO ACTION ON UPDATE NO ACTION; +GO + +-- Creating non-clustered index for FOREIGN KEY 'FK_StudentEnrollement' +CREATE INDEX [IX_FK_StudentEnrollement] +ON [dbo].[Enrollements] + ([StudentStudentId]); +GO + +-- Creating foreign key on [CourseCourseId] in table 'Enrollements' +ALTER TABLE [dbo].[Enrollements] +ADD CONSTRAINT [FK_CourseEnrollement] + FOREIGN KEY ([CourseCourseId]) + REFERENCES [dbo].[Courses] + ([CourseId]) + ON DELETE NO ACTION ON UPDATE NO ACTION; +GO + +-- Creating non-clustered index for FOREIGN KEY 'FK_CourseEnrollement' +CREATE INDEX [IX_FK_CourseEnrollement] +ON [dbo].[Enrollements] + ([CourseCourseId]); +GO + +-- -------------------------------------------------- +-- Script has ended +-- -------------------------------------------------- \ No newline at end of file diff --git a/src/Examples/EF6/Ex5_Store/EFModelFirstDemo-master/EFModelFirstDemo/ModelFirstDemoDB.tt b/src/Examples/EF6/Ex5_Store/EFModelFirstDemo-master/EFModelFirstDemo/ModelFirstDemoDB.tt new file mode 100644 index 000000000..9884e8f7d --- /dev/null +++ b/src/Examples/EF6/Ex5_Store/EFModelFirstDemo-master/EFModelFirstDemo/ModelFirstDemoDB.tt @@ -0,0 +1,733 @@ +<#@ template language="C#" debug="false" hostspecific="true"#> +<#@ include file="EF6.Utility.CS.ttinclude"#><#@ + output extension=".cs"#><# + +const string inputFile = @"ModelFirstDemoDB.edmx"; +var textTransform = DynamicTextTransformation.Create(this); +var code = new CodeGenerationTools(this); +var ef = new MetadataTools(this); +var typeMapper = new TypeMapper(code, ef, textTransform.Errors); +var fileManager = EntityFrameworkTemplateFileManager.Create(this); +var itemCollection = new EdmMetadataLoader(textTransform.Host, textTransform.Errors).CreateEdmItemCollection(inputFile); +var codeStringGenerator = new CodeStringGenerator(code, typeMapper, ef); + +if (!typeMapper.VerifyCaseInsensitiveTypeUniqueness(typeMapper.GetAllGlobalItems(itemCollection), inputFile)) +{ + return string.Empty; +} + +WriteHeader(codeStringGenerator, fileManager); + +foreach (var entity in typeMapper.GetItemsToGenerate(itemCollection)) +{ + fileManager.StartNewFile(entity.Name + ".cs"); + BeginNamespace(code); +#> +<#=codeStringGenerator.UsingDirectives(inHeader: false)#> +<#=codeStringGenerator.EntityClassOpening(entity)#> +{ +<# + var propertiesWithDefaultValues = typeMapper.GetPropertiesWithDefaultValues(entity); + var collectionNavigationProperties = typeMapper.GetCollectionNavigationProperties(entity); + var complexProperties = typeMapper.GetComplexProperties(entity); + + if (propertiesWithDefaultValues.Any() || collectionNavigationProperties.Any() || complexProperties.Any()) + { +#> + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] + public <#=code.Escape(entity)#>() + { +<# + foreach (var edmProperty in propertiesWithDefaultValues) + { +#> + this.<#=code.Escape(edmProperty)#> = <#=typeMapper.CreateLiteral(edmProperty.DefaultValue)#>; +<# + } + + foreach (var navigationProperty in collectionNavigationProperties) + { +#> + this.<#=code.Escape(navigationProperty)#> = new HashSet<<#=typeMapper.GetTypeName(navigationProperty.ToEndMember.GetEntityType())#>>(); +<# + } + + foreach (var complexProperty in complexProperties) + { +#> + this.<#=code.Escape(complexProperty)#> = new <#=typeMapper.GetTypeName(complexProperty.TypeUsage)#>(); +<# + } +#> + } + +<# + } + + var simpleProperties = typeMapper.GetSimpleProperties(entity); + if (simpleProperties.Any()) + { + foreach (var edmProperty in simpleProperties) + { +#> + <#=codeStringGenerator.Property(edmProperty)#> +<# + } + } + + if (complexProperties.Any()) + { +#> + +<# + foreach(var complexProperty in complexProperties) + { +#> + <#=codeStringGenerator.Property(complexProperty)#> +<# + } + } + + var navigationProperties = typeMapper.GetNavigationProperties(entity); + if (navigationProperties.Any()) + { +#> + +<# + foreach (var navigationProperty in navigationProperties) + { + if (navigationProperty.ToEndMember.RelationshipMultiplicity == RelationshipMultiplicity.Many) + { +#> + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] +<# + } +#> + <#=codeStringGenerator.NavigationProperty(navigationProperty)#> +<# + } + } +#> +} +<# + EndNamespace(code); +} + +foreach (var complex in typeMapper.GetItemsToGenerate(itemCollection)) +{ + fileManager.StartNewFile(complex.Name + ".cs"); + BeginNamespace(code); +#> +<#=codeStringGenerator.UsingDirectives(inHeader: false, includeCollections: false)#> +<#=Accessibility.ForType(complex)#> partial class <#=code.Escape(complex)#> +{ +<# + var complexProperties = typeMapper.GetComplexProperties(complex); + var propertiesWithDefaultValues = typeMapper.GetPropertiesWithDefaultValues(complex); + + if (propertiesWithDefaultValues.Any() || complexProperties.Any()) + { +#> + public <#=code.Escape(complex)#>() + { +<# + foreach (var edmProperty in propertiesWithDefaultValues) + { +#> + this.<#=code.Escape(edmProperty)#> = <#=typeMapper.CreateLiteral(edmProperty.DefaultValue)#>; +<# + } + + foreach (var complexProperty in complexProperties) + { +#> + this.<#=code.Escape(complexProperty)#> = new <#=typeMapper.GetTypeName(complexProperty.TypeUsage)#>(); +<# + } +#> + } + +<# + } + + var simpleProperties = typeMapper.GetSimpleProperties(complex); + if (simpleProperties.Any()) + { + foreach(var edmProperty in simpleProperties) + { +#> + <#=codeStringGenerator.Property(edmProperty)#> +<# + } + } + + if (complexProperties.Any()) + { +#> + +<# + foreach(var edmProperty in complexProperties) + { +#> + <#=codeStringGenerator.Property(edmProperty)#> +<# + } + } +#> +} +<# + EndNamespace(code); +} + +foreach (var enumType in typeMapper.GetEnumItemsToGenerate(itemCollection)) +{ + fileManager.StartNewFile(enumType.Name + ".cs"); + BeginNamespace(code); +#> +<#=codeStringGenerator.UsingDirectives(inHeader: false, includeCollections: false)#> +<# + if (typeMapper.EnumIsFlags(enumType)) + { +#> +[Flags] +<# + } +#> +<#=codeStringGenerator.EnumOpening(enumType)#> +{ +<# + var foundOne = false; + + foreach (MetadataItem member in typeMapper.GetEnumMembers(enumType)) + { + foundOne = true; +#> + <#=code.Escape(typeMapper.GetEnumMemberName(member))#> = <#=typeMapper.GetEnumMemberValue(member)#>, +<# + } + + if (foundOne) + { + this.GenerationEnvironment.Remove(this.GenerationEnvironment.Length - 3, 1); + } +#> +} +<# + EndNamespace(code); +} + +fileManager.Process(); + +#> +<#+ + +public void WriteHeader(CodeStringGenerator codeStringGenerator, EntityFrameworkTemplateFileManager fileManager) +{ + fileManager.StartHeader(); +#> +//------------------------------------------------------------------------------ +// +// <#=CodeGenerationTools.GetResourceString("Template_GeneratedCodeCommentLine1")#> +// +// <#=CodeGenerationTools.GetResourceString("Template_GeneratedCodeCommentLine2")#> +// <#=CodeGenerationTools.GetResourceString("Template_GeneratedCodeCommentLine3")#> +// +//------------------------------------------------------------------------------ +<#=codeStringGenerator.UsingDirectives(inHeader: true)#> +<#+ + fileManager.EndBlock(); +} + +public void BeginNamespace(CodeGenerationTools code) +{ + var codeNamespace = code.VsNamespaceSuggestion(); + if (!String.IsNullOrEmpty(codeNamespace)) + { +#> +namespace <#=code.EscapeNamespace(codeNamespace)#> +{ +<#+ + PushIndent(" "); + } +} + +public void EndNamespace(CodeGenerationTools code) +{ + if (!String.IsNullOrEmpty(code.VsNamespaceSuggestion())) + { + PopIndent(); +#> +} +<#+ + } +} + +public const string TemplateId = "CSharp_DbContext_Types_EF6"; + +public class CodeStringGenerator +{ + private readonly CodeGenerationTools _code; + private readonly TypeMapper _typeMapper; + private readonly MetadataTools _ef; + + public CodeStringGenerator(CodeGenerationTools code, TypeMapper typeMapper, MetadataTools ef) + { + ArgumentNotNull(code, "code"); + ArgumentNotNull(typeMapper, "typeMapper"); + ArgumentNotNull(ef, "ef"); + + _code = code; + _typeMapper = typeMapper; + _ef = ef; + } + + public string Property(EdmProperty edmProperty) + { + return string.Format( + CultureInfo.InvariantCulture, + "{0} {1} {2} {{ {3}get; {4}set; }}", + Accessibility.ForProperty(edmProperty), + _typeMapper.GetTypeName(edmProperty.TypeUsage), + _code.Escape(edmProperty), + _code.SpaceAfter(Accessibility.ForGetter(edmProperty)), + _code.SpaceAfter(Accessibility.ForSetter(edmProperty))); + } + + public string NavigationProperty(NavigationProperty navProp) + { + var endType = _typeMapper.GetTypeName(navProp.ToEndMember.GetEntityType()); + return string.Format( + CultureInfo.InvariantCulture, + "{0} {1} {2} {{ {3}get; {4}set; }}", + AccessibilityAndVirtual(Accessibility.ForNavigationProperty(navProp)), + navProp.ToEndMember.RelationshipMultiplicity == RelationshipMultiplicity.Many ? ("ICollection<" + endType + ">") : endType, + _code.Escape(navProp), + _code.SpaceAfter(Accessibility.ForGetter(navProp)), + _code.SpaceAfter(Accessibility.ForSetter(navProp))); + } + + public string AccessibilityAndVirtual(string accessibility) + { + return accessibility + (accessibility != "private" ? " virtual" : ""); + } + + public string EntityClassOpening(EntityType entity) + { + return string.Format( + CultureInfo.InvariantCulture, + "{0} {1}partial class {2}{3}", + Accessibility.ForType(entity), + _code.SpaceAfter(_code.AbstractOption(entity)), + _code.Escape(entity), + _code.StringBefore(" : ", _typeMapper.GetTypeName(entity.BaseType))); + } + + public string EnumOpening(SimpleType enumType) + { + return string.Format( + CultureInfo.InvariantCulture, + "{0} enum {1} : {2}", + Accessibility.ForType(enumType), + _code.Escape(enumType), + _code.Escape(_typeMapper.UnderlyingClrType(enumType))); + } + + public void WriteFunctionParameters(EdmFunction edmFunction, Action writeParameter) + { + var parameters = FunctionImportParameter.Create(edmFunction.Parameters, _code, _ef); + foreach (var parameter in parameters.Where(p => p.NeedsLocalVariable)) + { + var isNotNull = parameter.IsNullableOfT ? parameter.FunctionParameterName + ".HasValue" : parameter.FunctionParameterName + " != null"; + var notNullInit = "new ObjectParameter(\"" + parameter.EsqlParameterName + "\", " + parameter.FunctionParameterName + ")"; + var nullInit = "new ObjectParameter(\"" + parameter.EsqlParameterName + "\", typeof(" + TypeMapper.FixNamespaces(parameter.RawClrTypeName) + "))"; + writeParameter(parameter.LocalVariableName, isNotNull, notNullInit, nullInit); + } + } + + public string ComposableFunctionMethod(EdmFunction edmFunction, string modelNamespace) + { + var parameters = _typeMapper.GetParameters(edmFunction); + + return string.Format( + CultureInfo.InvariantCulture, + "{0} IQueryable<{1}> {2}({3})", + AccessibilityAndVirtual(Accessibility.ForMethod(edmFunction)), + _typeMapper.GetTypeName(_typeMapper.GetReturnType(edmFunction), modelNamespace), + _code.Escape(edmFunction), + string.Join(", ", parameters.Select(p => TypeMapper.FixNamespaces(p.FunctionParameterType) + " " + p.FunctionParameterName).ToArray())); + } + + public string ComposableCreateQuery(EdmFunction edmFunction, string modelNamespace) + { + var parameters = _typeMapper.GetParameters(edmFunction); + + return string.Format( + CultureInfo.InvariantCulture, + "return ((IObjectContextAdapter)this).ObjectContext.CreateQuery<{0}>(\"[{1}].[{2}]({3})\"{4});", + _typeMapper.GetTypeName(_typeMapper.GetReturnType(edmFunction), modelNamespace), + edmFunction.NamespaceName, + edmFunction.Name, + string.Join(", ", parameters.Select(p => "@" + p.EsqlParameterName).ToArray()), + _code.StringBefore(", ", string.Join(", ", parameters.Select(p => p.ExecuteParameterName).ToArray()))); + } + + public string FunctionMethod(EdmFunction edmFunction, string modelNamespace, bool includeMergeOption) + { + var parameters = _typeMapper.GetParameters(edmFunction); + var returnType = _typeMapper.GetReturnType(edmFunction); + + var paramList = String.Join(", ", parameters.Select(p => TypeMapper.FixNamespaces(p.FunctionParameterType) + " " + p.FunctionParameterName).ToArray()); + if (includeMergeOption) + { + paramList = _code.StringAfter(paramList, ", ") + "MergeOption mergeOption"; + } + + return string.Format( + CultureInfo.InvariantCulture, + "{0} {1} {2}({3})", + AccessibilityAndVirtual(Accessibility.ForMethod(edmFunction)), + returnType == null ? "int" : "ObjectResult<" + _typeMapper.GetTypeName(returnType, modelNamespace) + ">", + _code.Escape(edmFunction), + paramList); + } + + public string ExecuteFunction(EdmFunction edmFunction, string modelNamespace, bool includeMergeOption) + { + var parameters = _typeMapper.GetParameters(edmFunction); + var returnType = _typeMapper.GetReturnType(edmFunction); + + var callParams = _code.StringBefore(", ", String.Join(", ", parameters.Select(p => p.ExecuteParameterName).ToArray())); + if (includeMergeOption) + { + callParams = ", mergeOption" + callParams; + } + + return string.Format( + CultureInfo.InvariantCulture, + "return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction{0}(\"{1}\"{2});", + returnType == null ? "" : "<" + _typeMapper.GetTypeName(returnType, modelNamespace) + ">", + edmFunction.Name, + callParams); + } + + public string DbSet(EntitySet entitySet) + { + return string.Format( + CultureInfo.InvariantCulture, + "{0} virtual DbSet<{1}> {2} {{ get; set; }}", + Accessibility.ForReadOnlyProperty(entitySet), + _typeMapper.GetTypeName(entitySet.ElementType), + _code.Escape(entitySet)); + } + + public string UsingDirectives(bool inHeader, bool includeCollections = true) + { + return inHeader == string.IsNullOrEmpty(_code.VsNamespaceSuggestion()) + ? string.Format( + CultureInfo.InvariantCulture, + "{0}using System;{1}" + + "{2}", + inHeader ? Environment.NewLine : "", + includeCollections ? (Environment.NewLine + "using System.Collections.Generic;") : "", + inHeader ? "" : Environment.NewLine) + : ""; + } +} + +public class TypeMapper +{ + private const string ExternalTypeNameAttributeName = @"http://schemas.microsoft.com/ado/2006/04/codegeneration:ExternalTypeName"; + + private readonly System.Collections.IList _errors; + private readonly CodeGenerationTools _code; + private readonly MetadataTools _ef; + + public TypeMapper(CodeGenerationTools code, MetadataTools ef, System.Collections.IList errors) + { + ArgumentNotNull(code, "code"); + ArgumentNotNull(ef, "ef"); + ArgumentNotNull(errors, "errors"); + + _code = code; + _ef = ef; + _errors = errors; + } + + public static string FixNamespaces(string typeName) + { + return typeName.Replace("System.Data.Spatial.", "System.Data.Entity.Spatial."); + } + + public string GetTypeName(TypeUsage typeUsage) + { + return typeUsage == null ? null : GetTypeName(typeUsage.EdmType, _ef.IsNullable(typeUsage), modelNamespace: null); + } + + public string GetTypeName(EdmType edmType) + { + return GetTypeName(edmType, isNullable: null, modelNamespace: null); + } + + public string GetTypeName(TypeUsage typeUsage, string modelNamespace) + { + return typeUsage == null ? null : GetTypeName(typeUsage.EdmType, _ef.IsNullable(typeUsage), modelNamespace); + } + + public string GetTypeName(EdmType edmType, string modelNamespace) + { + return GetTypeName(edmType, isNullable: null, modelNamespace: modelNamespace); + } + + public string GetTypeName(EdmType edmType, bool? isNullable, string modelNamespace) + { + if (edmType == null) + { + return null; + } + + var collectionType = edmType as CollectionType; + if (collectionType != null) + { + return String.Format(CultureInfo.InvariantCulture, "ICollection<{0}>", GetTypeName(collectionType.TypeUsage, modelNamespace)); + } + + var typeName = _code.Escape(edmType.MetadataProperties + .Where(p => p.Name == ExternalTypeNameAttributeName) + .Select(p => (string)p.Value) + .FirstOrDefault()) + ?? (modelNamespace != null && edmType.NamespaceName != modelNamespace ? + _code.CreateFullName(_code.EscapeNamespace(edmType.NamespaceName), _code.Escape(edmType)) : + _code.Escape(edmType)); + + if (edmType is StructuralType) + { + return typeName; + } + + if (edmType is SimpleType) + { + var clrType = UnderlyingClrType(edmType); + if (!IsEnumType(edmType)) + { + typeName = _code.Escape(clrType); + } + + typeName = FixNamespaces(typeName); + + return clrType.IsValueType && isNullable == true ? + String.Format(CultureInfo.InvariantCulture, "Nullable<{0}>", typeName) : + typeName; + } + + throw new ArgumentException("edmType"); + } + + public Type UnderlyingClrType(EdmType edmType) + { + ArgumentNotNull(edmType, "edmType"); + + var primitiveType = edmType as PrimitiveType; + if (primitiveType != null) + { + return primitiveType.ClrEquivalentType; + } + + if (IsEnumType(edmType)) + { + return GetEnumUnderlyingType(edmType).ClrEquivalentType; + } + + return typeof(object); + } + + public object GetEnumMemberValue(MetadataItem enumMember) + { + ArgumentNotNull(enumMember, "enumMember"); + + var valueProperty = enumMember.GetType().GetProperty("Value"); + return valueProperty == null ? null : valueProperty.GetValue(enumMember, null); + } + + public string GetEnumMemberName(MetadataItem enumMember) + { + ArgumentNotNull(enumMember, "enumMember"); + + var nameProperty = enumMember.GetType().GetProperty("Name"); + return nameProperty == null ? null : (string)nameProperty.GetValue(enumMember, null); + } + + public System.Collections.IEnumerable GetEnumMembers(EdmType enumType) + { + ArgumentNotNull(enumType, "enumType"); + + var membersProperty = enumType.GetType().GetProperty("Members"); + return membersProperty != null + ? (System.Collections.IEnumerable)membersProperty.GetValue(enumType, null) + : Enumerable.Empty(); + } + + public bool EnumIsFlags(EdmType enumType) + { + ArgumentNotNull(enumType, "enumType"); + + var isFlagsProperty = enumType.GetType().GetProperty("IsFlags"); + return isFlagsProperty != null && (bool)isFlagsProperty.GetValue(enumType, null); + } + + public bool IsEnumType(GlobalItem edmType) + { + ArgumentNotNull(edmType, "edmType"); + + return edmType.GetType().Name == "EnumType"; + } + + public PrimitiveType GetEnumUnderlyingType(EdmType enumType) + { + ArgumentNotNull(enumType, "enumType"); + + return (PrimitiveType)enumType.GetType().GetProperty("UnderlyingType").GetValue(enumType, null); + } + + public string CreateLiteral(object value) + { + if (value == null || value.GetType() != typeof(TimeSpan)) + { + return _code.CreateLiteral(value); + } + + return string.Format(CultureInfo.InvariantCulture, "new TimeSpan({0})", ((TimeSpan)value).Ticks); + } + + public bool VerifyCaseInsensitiveTypeUniqueness(IEnumerable types, string sourceFile) + { + ArgumentNotNull(types, "types"); + ArgumentNotNull(sourceFile, "sourceFile"); + + var hash = new HashSet(StringComparer.InvariantCultureIgnoreCase); + if (types.Any(item => !hash.Add(item))) + { + _errors.Add( + new CompilerError(sourceFile, -1, -1, "6023", + String.Format(CultureInfo.CurrentCulture, CodeGenerationTools.GetResourceString("Template_CaseInsensitiveTypeConflict")))); + return false; + } + return true; + } + + public IEnumerable GetEnumItemsToGenerate(IEnumerable itemCollection) + { + return GetItemsToGenerate(itemCollection) + .Where(e => IsEnumType(e)); + } + + public IEnumerable GetItemsToGenerate(IEnumerable itemCollection) where T: EdmType + { + return itemCollection + .OfType() + .Where(i => !i.MetadataProperties.Any(p => p.Name == ExternalTypeNameAttributeName)) + .OrderBy(i => i.Name); + } + + public IEnumerable GetAllGlobalItems(IEnumerable itemCollection) + { + return itemCollection + .Where(i => i is EntityType || i is ComplexType || i is EntityContainer || IsEnumType(i)) + .Select(g => GetGlobalItemName(g)); + } + + public string GetGlobalItemName(GlobalItem item) + { + if (item is EdmType) + { + return ((EdmType)item).Name; + } + else + { + return ((EntityContainer)item).Name; + } + } + + public IEnumerable GetSimpleProperties(EntityType type) + { + return type.Properties.Where(p => p.TypeUsage.EdmType is SimpleType && p.DeclaringType == type); + } + + public IEnumerable GetSimpleProperties(ComplexType type) + { + return type.Properties.Where(p => p.TypeUsage.EdmType is SimpleType && p.DeclaringType == type); + } + + public IEnumerable GetComplexProperties(EntityType type) + { + return type.Properties.Where(p => p.TypeUsage.EdmType is ComplexType && p.DeclaringType == type); + } + + public IEnumerable GetComplexProperties(ComplexType type) + { + return type.Properties.Where(p => p.TypeUsage.EdmType is ComplexType && p.DeclaringType == type); + } + + public IEnumerable GetPropertiesWithDefaultValues(EntityType type) + { + return type.Properties.Where(p => p.TypeUsage.EdmType is SimpleType && p.DeclaringType == type && p.DefaultValue != null); + } + + public IEnumerable GetPropertiesWithDefaultValues(ComplexType type) + { + return type.Properties.Where(p => p.TypeUsage.EdmType is SimpleType && p.DeclaringType == type && p.DefaultValue != null); + } + + public IEnumerable GetNavigationProperties(EntityType type) + { + return type.NavigationProperties.Where(np => np.DeclaringType == type); + } + + public IEnumerable GetCollectionNavigationProperties(EntityType type) + { + return type.NavigationProperties.Where(np => np.DeclaringType == type && np.ToEndMember.RelationshipMultiplicity == RelationshipMultiplicity.Many); + } + + public FunctionParameter GetReturnParameter(EdmFunction edmFunction) + { + ArgumentNotNull(edmFunction, "edmFunction"); + + var returnParamsProperty = edmFunction.GetType().GetProperty("ReturnParameters"); + return returnParamsProperty == null + ? edmFunction.ReturnParameter + : ((IEnumerable)returnParamsProperty.GetValue(edmFunction, null)).FirstOrDefault(); + } + + public bool IsComposable(EdmFunction edmFunction) + { + ArgumentNotNull(edmFunction, "edmFunction"); + + var isComposableProperty = edmFunction.GetType().GetProperty("IsComposableAttribute"); + return isComposableProperty != null && (bool)isComposableProperty.GetValue(edmFunction, null); + } + + public IEnumerable GetParameters(EdmFunction edmFunction) + { + return FunctionImportParameter.Create(edmFunction.Parameters, _code, _ef); + } + + public TypeUsage GetReturnType(EdmFunction edmFunction) + { + var returnParam = GetReturnParameter(edmFunction); + return returnParam == null ? null : _ef.GetElementType(returnParam.TypeUsage); + } + + public bool GenerateMergeOptionFunction(EdmFunction edmFunction, bool includeMergeOption) + { + var returnType = GetReturnType(edmFunction); + return !includeMergeOption && returnType != null && returnType.EdmType.BuiltInTypeKind == BuiltInTypeKind.EntityType; + } +} + +public static void ArgumentNotNull(T arg, string name) where T : class +{ + if (arg == null) + { + throw new ArgumentNullException(name); + } +} +#> \ No newline at end of file diff --git a/src/Examples/EF6/Ex5_Store/EFModelFirstDemo-master/EFModelFirstDemo/Program.cs b/src/Examples/EF6/Ex5_Store/EFModelFirstDemo-master/EFModelFirstDemo/Program.cs new file mode 100644 index 000000000..149fdf087 --- /dev/null +++ b/src/Examples/EF6/Ex5_Store/EFModelFirstDemo-master/EFModelFirstDemo/Program.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace EFModelFirstDemo +{ + class Program + { + static void Main(string[] args) + { + + + } + } +} diff --git a/src/Examples/EF6/Ex5_Store/EFModelFirstDemo-master/EFModelFirstDemo/Properties/AssemblyInfo.cs b/src/Examples/EF6/Ex5_Store/EFModelFirstDemo-master/EFModelFirstDemo/Properties/AssemblyInfo.cs new file mode 100644 index 000000000..2ac11bb52 --- /dev/null +++ b/src/Examples/EF6/Ex5_Store/EFModelFirstDemo-master/EFModelFirstDemo/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("EFModelFirstDemo")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("EFModelFirstDemo")] +[assembly: AssemblyCopyright("Copyright © 2018")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("e617d310-1925-41e4-aac3-a23c78b7d420")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/src/Examples/EF6/Ex5_Store/EFModelFirstDemo-master/EFModelFirstDemo/Student.cs b/src/Examples/EF6/Ex5_Store/EFModelFirstDemo-master/EFModelFirstDemo/Student.cs new file mode 100644 index 000000000..e6ba0e2e4 --- /dev/null +++ b/src/Examples/EF6/Ex5_Store/EFModelFirstDemo-master/EFModelFirstDemo/Student.cs @@ -0,0 +1,31 @@ +//------------------------------------------------------------------------------ +// +// This code was generated from a template. +// +// Manual changes to this file may cause unexpected behavior in your application. +// Manual changes to this file will be overwritten if the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace EFModelFirstDemo +{ + using System; + using System.Collections.Generic; + + public partial class Student + { + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] + public Student() + { + this.Enrollements = new HashSet(); + } + + public int StudentId { get; set; } + public string FirstName { get; set; } + public string LastName { get; set; } + public System.DateTime EnrollementDate { get; set; } + + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] + public virtual ICollection Enrollements { get; set; } + } +} diff --git a/src/Examples/EF6/Ex5_Store/EFModelFirstDemo-master/EFModelFirstDemo/packages.config b/src/Examples/EF6/Ex5_Store/EFModelFirstDemo-master/EFModelFirstDemo/packages.config new file mode 100644 index 000000000..b3daf0d6c --- /dev/null +++ b/src/Examples/EF6/Ex5_Store/EFModelFirstDemo-master/EFModelFirstDemo/packages.config @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/src/Examples/EF6/Ex5_Store/Ex6_CRM.csproj b/src/Examples/EF6/Ex5_Store/Ex6_CRM.csproj new file mode 100644 index 000000000..5ff84d9e4 --- /dev/null +++ b/src/Examples/EF6/Ex5_Store/Ex6_CRM.csproj @@ -0,0 +1,123 @@ + + + + + Debug + AnyCPU + {9E4E33FD-1644-4AD1-9F6C-42389F7D3647} + WinExe + Ex5_Store + Ex5_Store + v4.8 + 512 + true + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + True + True + EFCRM.tt + + + Form + + + FrmEx6CRM.cs + + + + + + + + + + + + + + + + + + + + + + FrmEx6CRM.cs + + + ResXFileCodeGenerator + Resources.Designer.cs + Designer + + + True + Resources.resx + + + + EFCRM.efmodel + + + SettingsSingleFileGenerator + Settings.Designer.cs + + + True + Settings.settings + True + + + + + + + + 6.4.4 + + + + + TextTemplatingFileGenerator + EFCRM.cs + + + + + + + \ No newline at end of file diff --git a/src/Examples/EF6/Ex5_Store/FrmEx6CRM.Designer.cs b/src/Examples/EF6/Ex5_Store/FrmEx6CRM.Designer.cs new file mode 100644 index 000000000..0d4b86197 --- /dev/null +++ b/src/Examples/EF6/Ex5_Store/FrmEx6CRM.Designer.cs @@ -0,0 +1,63 @@ + +namespace Ex6_CRM +{ + partial class FrmEx6CRM + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + this.label1 = new System.Windows.Forms.Label(); + this.SuspendLayout(); + // + // label1 + // + this.label1.AutoSize = true; + this.label1.Location = new System.Drawing.Point(251, 165); + this.label1.Name = "label1"; + this.label1.Size = new System.Drawing.Size(107, 20); + this.label1.TabIndex = 0; + this.label1.Text = "No COde yet.."; + // + // FrmEx5Store + // + this.AutoScaleDimensions = new System.Drawing.SizeF(9F, 20F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(800, 450); + this.Controls.Add(this.label1); + this.Name = "FrmEx5Store"; + this.Text = "Ex 5 Store"; + this.Load += new System.EventHandler(this.FrmEx5Store_Load); + this.ResumeLayout(false); + this.PerformLayout(); + + } + + #endregion + + private System.Windows.Forms.Label label1; + } +} + diff --git a/src/Examples/EF6/Ex5_Store/FrmEx6CRM.cs b/src/Examples/EF6/Ex5_Store/FrmEx6CRM.cs new file mode 100644 index 000000000..89ba08f37 --- /dev/null +++ b/src/Examples/EF6/Ex5_Store/FrmEx6CRM.cs @@ -0,0 +1,27 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace Ex6_CRM +{ + // Ordering system + + public partial class FrmEx6CRM : Form + { + public FrmEx6CRM() + { + InitializeComponent(); + } + + private void FrmEx5Store_Load(object sender, EventArgs e) + { + + } + } +} diff --git a/src/Examples/EF6/Ex5_Store/FrmEx6CRM.resx b/src/Examples/EF6/Ex5_Store/FrmEx6CRM.resx new file mode 100644 index 000000000..1af7de150 --- /dev/null +++ b/src/Examples/EF6/Ex5_Store/FrmEx6CRM.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/src/Examples/EF6/Ex5_Store/Generated/Address.generated.cs b/src/Examples/EF6/Ex5_Store/Generated/Address.generated.cs new file mode 100644 index 000000000..3888da8c6 --- /dev/null +++ b/src/Examples/EF6/Ex5_Store/Generated/Address.generated.cs @@ -0,0 +1,97 @@ +//------------------------------------------------------------------------------ +// +// This code was generated from a template. +// +// Manual changes to this file may cause unexpected behavior in your application. +// Manual changes to this file will be overwritten if the code is regenerated. +// +// Produced by Entity Framework Visual Editor v3.0.7.2 +// Source: https://github.com/msawczyn/EFDesigner +// Visual Studio Marketplace: https://marketplace.visualstudio.com/items?itemName=michaelsawczyn.EFDesigner +// Documentation: https://msawczyn.github.io/EFDesigner/ +// License (MIT): https://github.com/msawczyn/EFDesigner/blob/master/LICENSE +// +//------------------------------------------------------------------------------ + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using System.Linq; +using System.Runtime.CompilerServices; + +namespace Ex5_Store +{ + public partial class Address + { + partial void Init(); + + /// + /// Default constructor + /// + public Address() + { + Opens = new System.Collections.Generic.HashSet(); + Tasks = new System.Collections.Generic.HashSet(); + + Init(); + } + + /************************************************************************* + * Properties + *************************************************************************/ + + /// + /// Identity, Indexed, Required + /// Unique identifier + /// + [Key] + [Required] + [System.ComponentModel.Description("Unique identifier")] + public long AddressId { get; set; } + + /// + /// Max length = 125 + /// + [MaxLength(125)] + [StringLength(125)] + public string PropertyType { get; set; } + + public string Unit { get; set; } + + public string Number { get; set; } + + public string StreetLine1 { get; set; } + + public string StreetType { get; set; } + + public string StreetLine2 { get; set; } + + public string Suburb { get; set; } + + public string PostalCode { get; set; } + + public string State { get; set; } + + public string Country { get; set; } + + /// + /// Max length = 125 + /// + [MaxLength(125)] + [StringLength(125)] + public string Sync { get; set; } + + /************************************************************************* + * Navigation properties + *************************************************************************/ + + public virtual ICollection Opens { get; private set; } + + public virtual ICollection Tasks { get; private set; } + + } +} + diff --git a/src/Examples/EF6/Ex5_Store/Generated/Agent.generated.cs b/src/Examples/EF6/Ex5_Store/Generated/Agent.generated.cs new file mode 100644 index 000000000..6fee17711 --- /dev/null +++ b/src/Examples/EF6/Ex5_Store/Generated/Agent.generated.cs @@ -0,0 +1,115 @@ +//------------------------------------------------------------------------------ +// +// This code was generated from a template. +// +// Manual changes to this file may cause unexpected behavior in your application. +// Manual changes to this file will be overwritten if the code is regenerated. +// +// Produced by Entity Framework Visual Editor v3.0.7.2 +// Source: https://github.com/msawczyn/EFDesigner +// Visual Studio Marketplace: https://marketplace.visualstudio.com/items?itemName=michaelsawczyn.EFDesigner +// Documentation: https://msawczyn.github.io/EFDesigner/ +// License (MIT): https://github.com/msawczyn/EFDesigner/blob/master/LICENSE +// +//------------------------------------------------------------------------------ + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using System.Linq; +using System.Runtime.CompilerServices; + +namespace Ex5_Store +{ + public partial class Agent + { + partial void Init(); + + /// + /// Default constructor. Protected due to required properties, but present because EF needs it. + /// + protected Agent() + { + Init(); + } + + /// + /// Replaces default constructor, since it's protected. Caller assumes responsibility for setting all required values before saving. + /// + public static Agent CreateAgentUnsafe() + { + return new Agent(); + } + + /// + /// Public constructor with required data + /// + /// + public Agent(global::Ex5_Store.Open open) + { + if (open == null) throw new ArgumentNullException(nameof(open)); + this.Open = open; + open.Agents.Add(this); + + Init(); + } + + /// + /// Static create function (for use in LINQ queries, etc.) + /// + /// + public static Agent Create(global::Ex5_Store.Open open) + { + return new Agent(open); + } + + /************************************************************************* + * Properties + *************************************************************************/ + + /// + /// Identity, Indexed, Required + /// Unique identifier + /// + [Key] + [Required] + [System.ComponentModel.Description("Unique identifier")] + public long AgentId { get; set; } + + public string FirstName { get; set; } + + public string LastName { get; set; } + + public string Email { get; set; } + + /// + /// Max length = 25 + /// + [MaxLength(25)] + [StringLength(25)] + public string Phone { get; set; } + + public string Notes { get; set; } + + /// + /// Max length = 125 + /// + [MaxLength(125)] + [StringLength(125)] + public string Sync { get; set; } + + /************************************************************************* + * Navigation properties + *************************************************************************/ + + /// + /// Required + /// + public virtual global::Ex5_Store.Open Open { get; set; } + + } +} + diff --git a/src/Examples/EF6/Ex5_Store/Generated/Audit.generated.cs b/src/Examples/EF6/Ex5_Store/Generated/Audit.generated.cs new file mode 100644 index 000000000..79b5324cf --- /dev/null +++ b/src/Examples/EF6/Ex5_Store/Generated/Audit.generated.cs @@ -0,0 +1,145 @@ +//------------------------------------------------------------------------------ +// +// This code was generated from a template. +// +// Manual changes to this file may cause unexpected behavior in your application. +// Manual changes to this file will be overwritten if the code is regenerated. +// +// Produced by Entity Framework Visual Editor v3.0.7.2 +// Source: https://github.com/msawczyn/EFDesigner +// Visual Studio Marketplace: https://marketplace.visualstudio.com/items?itemName=michaelsawczyn.EFDesigner +// Documentation: https://msawczyn.github.io/EFDesigner/ +// License (MIT): https://github.com/msawczyn/EFDesigner/blob/master/LICENSE +// +//------------------------------------------------------------------------------ + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using System.Linq; +using System.Runtime.CompilerServices; + +namespace Ex5_Store +{ + public partial class Audit + { + partial void Init(); + + /// + /// Default constructor. Protected due to required properties, but present because EF needs it. + /// + protected Audit() + { + Init(); + } + + /// + /// Replaces default constructor, since it's protected. Caller assumes responsibility for setting all required values before saving. + /// + public static Audit CreateAuditUnsafe() + { + return new Audit(); + } + + /// + /// Public constructor with required data + /// + /// + /// + /// + /// + /// + /// + public Audit(DateTime createdat, DateTime updatedat, string createdby, string lastmodifieddby, bool deleted, global::Ex5_Store.Tasks tasks) + { + this.CreatedAt = createdat; + + this.UpdatedAt = updatedat; + + if (string.IsNullOrEmpty(createdby)) throw new ArgumentNullException(nameof(createdby)); + this.Createdby = createdby; + + if (string.IsNullOrEmpty(lastmodifieddby)) throw new ArgumentNullException(nameof(lastmodifieddby)); + this.LastModifieddby = lastmodifieddby; + + this.Deleted = deleted; + + if (tasks == null) throw new ArgumentNullException(nameof(tasks)); + this.Tasks = tasks; + tasks.Audits.Add(this); + + Init(); + } + + /// + /// Static create function (for use in LINQ queries, etc.) + /// + /// + /// + /// + /// + /// + /// + public static Audit Create(DateTime createdat, DateTime updatedat, string createdby, string lastmodifieddby, bool deleted, global::Ex5_Store.Tasks tasks) + { + return new Audit(createdat, updatedat, createdby, lastmodifieddby, deleted, tasks); + } + + /************************************************************************* + * Properties + *************************************************************************/ + + /// + /// Identity, Indexed, Required + /// Unique identifier + /// + [Key] + [Required] + [System.ComponentModel.Description("Unique identifier")] + public long Id { get; set; } + + /// + /// Required + /// + [Required] + public DateTime CreatedAt { get; set; } + + /// + /// Required + /// + [Required] + public DateTime UpdatedAt { get; set; } + + /// + /// Required + /// + [Required] + public string Createdby { get; set; } + + /// + /// Required + /// + [Required] + public string LastModifieddby { get; set; } + + /// + /// Required + /// + [Required] + public bool Deleted { get; set; } + + /************************************************************************* + * Navigation properties + *************************************************************************/ + + /// + /// Required + /// + public virtual global::Ex5_Store.Tasks Tasks { get; set; } + + } +} + diff --git a/src/Examples/EF6/Ex5_Store/Generated/EFCRM.generated.cs b/src/Examples/EF6/Ex5_Store/Generated/EFCRM.generated.cs new file mode 100644 index 000000000..64e1a008c --- /dev/null +++ b/src/Examples/EF6/Ex5_Store/Generated/EFCRM.generated.cs @@ -0,0 +1,275 @@ +//------------------------------------------------------------------------------ +// +// This code was generated from a template. +// +// Manual changes to this file may cause unexpected behavior in your application. +// Manual changes to this file will be overwritten if the code is regenerated. +// +// Produced by Entity Framework Visual Editor v3.0.7.2 +// Source: https://github.com/msawczyn/EFDesigner +// Visual Studio Marketplace: https://marketplace.visualstudio.com/items?itemName=michaelsawczyn.EFDesigner +// Documentation: https://msawczyn.github.io/EFDesigner/ +// License (MIT): https://github.com/msawczyn/EFDesigner/blob/master/LICENSE +// +//------------------------------------------------------------------------------ + +using System; +using System.Collections.Generic; +using System.Linq; +using System.ComponentModel.DataAnnotations.Schema; +using System.Data.Entity; +using System.Data.Entity.Infrastructure.Annotations; + +namespace Ex5_Store +{ + /// + public partial class EFCRM : DbContext + { + #region DbSets + public virtual System.Data.Entity.DbSet Addresses { get; set; } + public virtual System.Data.Entity.DbSet Agents { get; set; } + public virtual System.Data.Entity.DbSet Audits { get; set; } + public virtual System.Data.Entity.DbSet Features { get; set; } + public virtual System.Data.Entity.DbSet Opens { get; set; } + public virtual System.Data.Entity.DbSet People { get; set; } + public virtual System.Data.Entity.DbSet PropertyStatus { get; set; } + public virtual System.Data.Entity.DbSet Tasks { get; set; } + public virtual System.Data.Entity.DbSet Templates { get; set; } + public virtual System.Data.Entity.DbSet Viewings { get; set; } + #endregion DbSets + + #region Constructors + + partial void CustomInit(); + + /// + /// Default connection string + /// + public static string ConnectionString { get; set; } = @"Data Source=(localdb)\mssqllocaldb;Initial Catalog=RE_CRM;Integrated Security=True;MultipleActiveResultSets=True"; + /// + public EFCRM() : base(ConnectionString) + { + Configuration.LazyLoadingEnabled = true; + Configuration.ProxyCreationEnabled = true; + System.Data.Entity.Database.SetInitializer(new EFCRMDatabaseInitializer()); + CustomInit(); + } + + /// + public EFCRM(string connectionString) : base(connectionString) + { + Configuration.LazyLoadingEnabled = true; + Configuration.ProxyCreationEnabled = true; + System.Data.Entity.Database.SetInitializer(new EFCRMDatabaseInitializer()); + CustomInit(); + } + + /// + public EFCRM(string connectionString, System.Data.Entity.Infrastructure.DbCompiledModel model) : base(connectionString, model) + { + Configuration.LazyLoadingEnabled = true; + Configuration.ProxyCreationEnabled = true; + System.Data.Entity.Database.SetInitializer(new EFCRMDatabaseInitializer()); + CustomInit(); + } + + /// + public EFCRM(System.Data.Common.DbConnection existingConnection, bool contextOwnsConnection) : base(existingConnection, contextOwnsConnection) + { + Configuration.LazyLoadingEnabled = true; + Configuration.ProxyCreationEnabled = true; + System.Data.Entity.Database.SetInitializer(new EFCRMDatabaseInitializer()); + CustomInit(); + } + + /// + public EFCRM(System.Data.Common.DbConnection existingConnection, System.Data.Entity.Infrastructure.DbCompiledModel model, bool contextOwnsConnection) : base(existingConnection, model, contextOwnsConnection) + { + Configuration.LazyLoadingEnabled = true; + Configuration.ProxyCreationEnabled = true; + System.Data.Entity.Database.SetInitializer(new EFCRMDatabaseInitializer()); + CustomInit(); + } + + /// + public EFCRM(System.Data.Entity.Infrastructure.DbCompiledModel model) : base(model) + { + Configuration.LazyLoadingEnabled = true; + Configuration.ProxyCreationEnabled = true; + System.Data.Entity.Database.SetInitializer(new EFCRMDatabaseInitializer()); + CustomInit(); + } + + /// + public EFCRM(System.Data.Entity.Core.Objects.ObjectContext objectContext, bool dbContextOwnsObjectContext) : base(objectContext, dbContextOwnsObjectContext) + { + Configuration.LazyLoadingEnabled = true; + Configuration.ProxyCreationEnabled = true; + System.Data.Entity.Database.SetInitializer(new EFCRMDatabaseInitializer()); + CustomInit(); + } + + #endregion Constructors + + partial void OnModelCreatingImpl(System.Data.Entity.DbModelBuilder modelBuilder); + partial void OnModelCreatedImpl(System.Data.Entity.DbModelBuilder modelBuilder); + + /// + protected override void OnModelCreating(System.Data.Entity.DbModelBuilder modelBuilder) + { + base.OnModelCreating(modelBuilder); + OnModelCreatingImpl(modelBuilder); + + modelBuilder.HasDefaultSchema("dbo"); + + modelBuilder.Entity() + .ToTable("Addresses") + .HasKey(t => t.AddressId); + modelBuilder.Entity() + .Property(t => t.AddressId) + .IsRequired() + .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity); + modelBuilder.Entity() + .Property(t => t.PropertyType) + .HasMaxLength(125); + modelBuilder.Entity() + .Property(t => t.Sync) + .HasMaxLength(125); + + modelBuilder.Entity() + .ToTable("Agents") + .HasKey(t => t.AgentId); + modelBuilder.Entity() + .Property(t => t.AgentId) + .IsRequired() + .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity); + modelBuilder.Entity() + .Property(t => t.Phone) + .HasMaxLength(25); + modelBuilder.Entity() + .Property(t => t.Sync) + .HasMaxLength(125); + modelBuilder.Entity() + .HasRequired(x => x.Open) + .WithMany(x => x.Agents) + .Map(x => x.MapKey("OpenOpenId")); + + modelBuilder.Entity() + .ToTable("Audits") + .HasKey(t => t.Id); + modelBuilder.Entity() + .Property(t => t.Id) + .IsRequired() + .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity); + modelBuilder.Entity() + .Property(t => t.CreatedAt) + .IsRequired(); + modelBuilder.Entity() + .Property(t => t.UpdatedAt) + .IsRequired(); + modelBuilder.Entity() + .Property(t => t.Createdby) + .IsRequired(); + modelBuilder.Entity() + .Property(t => t.LastModifieddby) + .IsRequired(); + modelBuilder.Entity() + .Property(t => t.Deleted) + .IsRequired(); + modelBuilder.Entity() + .HasRequired(x => x.Tasks) + .WithMany(x => x.Audits) + .Map(x => x.MapKey("TasksId")); + + modelBuilder.Entity() + .ToTable("Features") + .HasKey(t => t.Id); + modelBuilder.Entity() + .Property(t => t.Id) + .IsRequired() + .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity); + + modelBuilder.Entity() + .ToTable("Opens") + .HasKey(t => t.OpenId); + modelBuilder.Entity() + .Property(t => t.OpenId) + .IsRequired() + .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity); + modelBuilder.Entity() + .Property(t => t.Sync) + .HasMaxLength(125); + modelBuilder.Entity() + .HasRequired(x => x.Address) + .WithMany(x => x.Opens) + .Map(x => x.MapKey("AddressAddressId")); + + modelBuilder.Entity() + .ToTable("People") + .HasKey(t => t.PeopleId); + modelBuilder.Entity() + .Property(t => t.PeopleId) + .IsRequired() + .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity); + modelBuilder.Entity() + .Property(t => t.Phone) + .HasMaxLength(25); + modelBuilder.Entity() + .Property(t => t.Sync) + .HasMaxLength(125); + + modelBuilder.Entity() + .ToTable("PropertyStatus") + .HasKey(t => t.Id); + modelBuilder.Entity() + .Property(t => t.Id) + .IsRequired() + .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity); + + modelBuilder.Entity() + .ToTable("Tasks") + .HasKey(t => t.Id); + modelBuilder.Entity() + .Property(t => t.Id) + .IsRequired() + .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity); + modelBuilder.Entity() + .HasRequired(x => x.Person) + .WithMany(x => x.Tasks) + .Map(x => x.MapKey("PersonPeopleId")); + modelBuilder.Entity() + .HasRequired(x => x.Address) + .WithMany(x => x.Tasks) + .Map(x => x.MapKey("AddressAddressId")); + + modelBuilder.Entity() + .ToTable("Templates") + .HasKey(t => t.Id); + modelBuilder.Entity() + .Property(t => t.Id) + .IsRequired() + .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity); + + modelBuilder.Entity() + .ToTable("Viewings") + .HasKey(t => t.Id); + modelBuilder.Entity() + .Property(t => t.Id) + .IsRequired() + .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity); + modelBuilder.Entity() + .Property(t => t.Sync) + .HasMaxLength(125); + modelBuilder.Entity() + .HasRequired(x => x.Open) + .WithMany(x => x.Viewings) + .Map(x => x.MapKey("OpenOpenId")); + modelBuilder.Entity() + .HasRequired(x => x.Person) + .WithMany(x => x.Viewings) + .Map(x => x.MapKey("PersonPeopleId")); + + OnModelCreatedImpl(modelBuilder); + } + } +} diff --git a/src/Examples/EF6/Ex5_Store/Generated/EFCRMDatabaseInitializer.generated.cs b/src/Examples/EF6/Ex5_Store/Generated/EFCRMDatabaseInitializer.generated.cs new file mode 100644 index 000000000..dc8959382 --- /dev/null +++ b/src/Examples/EF6/Ex5_Store/Generated/EFCRMDatabaseInitializer.generated.cs @@ -0,0 +1,24 @@ +//------------------------------------------------------------------------------ +// +// This code was generated from a template. +// +// Manual changes to this file may cause unexpected behavior in your application. +// Manual changes to this file will be overwritten if the code is regenerated. +// +// Produced by Entity Framework Visual Editor v3.0.7.2 +// Source: https://github.com/msawczyn/EFDesigner +// Visual Studio Marketplace: https://marketplace.visualstudio.com/items?itemName=michaelsawczyn.EFDesigner +// Documentation: https://msawczyn.github.io/EFDesigner/ +// License (MIT): https://github.com/msawczyn/EFDesigner/blob/master/LICENSE +// +//------------------------------------------------------------------------------ + +using System.Data.Entity; + +namespace Ex5_Store +{ + /// + public partial class EFCRMDatabaseInitializer : MigrateDatabaseToLatestVersion + { + } +} diff --git a/src/Examples/EF6/Ex5_Store/Generated/EFCRMDbMigrationConfiguration.generated.cs b/src/Examples/EF6/Ex5_Store/Generated/EFCRMDbMigrationConfiguration.generated.cs new file mode 100644 index 000000000..3f8a96723 --- /dev/null +++ b/src/Examples/EF6/Ex5_Store/Generated/EFCRMDbMigrationConfiguration.generated.cs @@ -0,0 +1,33 @@ +//------------------------------------------------------------------------------ +// +// This code was generated from a template. +// +// Manual changes to this file may cause unexpected behavior in your application. +// Manual changes to this file will be overwritten if the code is regenerated. +// +// Produced by Entity Framework Visual Editor v3.0.7.2 +// Source: https://github.com/msawczyn/EFDesigner +// Visual Studio Marketplace: https://marketplace.visualstudio.com/items?itemName=michaelsawczyn.EFDesigner +// Documentation: https://msawczyn.github.io/EFDesigner/ +// License (MIT): https://github.com/msawczyn/EFDesigner/blob/master/LICENSE +// +//------------------------------------------------------------------------------ + +using System.Data.Entity.Migrations; + +namespace Migrations +{ + /// + public sealed partial class EFCRMDbMigrationConfiguration : DbMigrationsConfiguration + { + partial void Init(); + + /// + public EFCRMDbMigrationConfiguration() + { + AutomaticMigrationsEnabled = true; + AutomaticMigrationDataLossAllowed = false; + Init(); + } + } +} diff --git a/src/Examples/EF6/Ex5_Store/Generated/Features.generated.cs b/src/Examples/EF6/Ex5_Store/Generated/Features.generated.cs new file mode 100644 index 000000000..c36ec6c86 --- /dev/null +++ b/src/Examples/EF6/Ex5_Store/Generated/Features.generated.cs @@ -0,0 +1,54 @@ +//------------------------------------------------------------------------------ +// +// This code was generated from a template. +// +// Manual changes to this file may cause unexpected behavior in your application. +// Manual changes to this file will be overwritten if the code is regenerated. +// +// Produced by Entity Framework Visual Editor v3.0.7.2 +// Source: https://github.com/msawczyn/EFDesigner +// Visual Studio Marketplace: https://marketplace.visualstudio.com/items?itemName=michaelsawczyn.EFDesigner +// Documentation: https://msawczyn.github.io/EFDesigner/ +// License (MIT): https://github.com/msawczyn/EFDesigner/blob/master/LICENSE +// +//------------------------------------------------------------------------------ + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using System.Linq; +using System.Runtime.CompilerServices; + +namespace Ex5_Store +{ + public partial class Features + { + partial void Init(); + + /// + /// Default constructor + /// + public Features() + { + Init(); + } + + /************************************************************************* + * Properties + *************************************************************************/ + + /// + /// Identity, Indexed, Required + /// Unique identifier + /// + [Key] + [Required] + [System.ComponentModel.Description("Unique identifier")] + public long Id { get; set; } + + } +} + diff --git a/src/Examples/EF6/Ex5_Store/Generated/Open.generated.cs b/src/Examples/EF6/Ex5_Store/Generated/Open.generated.cs new file mode 100644 index 000000000..3278350dc --- /dev/null +++ b/src/Examples/EF6/Ex5_Store/Generated/Open.generated.cs @@ -0,0 +1,115 @@ +//------------------------------------------------------------------------------ +// +// This code was generated from a template. +// +// Manual changes to this file may cause unexpected behavior in your application. +// Manual changes to this file will be overwritten if the code is regenerated. +// +// Produced by Entity Framework Visual Editor v3.0.7.2 +// Source: https://github.com/msawczyn/EFDesigner +// Visual Studio Marketplace: https://marketplace.visualstudio.com/items?itemName=michaelsawczyn.EFDesigner +// Documentation: https://msawczyn.github.io/EFDesigner/ +// License (MIT): https://github.com/msawczyn/EFDesigner/blob/master/LICENSE +// +//------------------------------------------------------------------------------ + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using System.Linq; +using System.Runtime.CompilerServices; + +namespace Ex5_Store +{ + public partial class Open + { + partial void Init(); + + /// + /// Default constructor. Protected due to required properties, but present because EF needs it. + /// + protected Open() + { + Agents = new System.Collections.Generic.HashSet(); + Viewings = new System.Collections.Generic.HashSet(); + + Init(); + } + + /// + /// Replaces default constructor, since it's protected. Caller assumes responsibility for setting all required values before saving. + /// + public static Open CreateOpenUnsafe() + { + return new Open(); + } + + /// + /// Public constructor with required data + /// + /// + public Open(global::Ex5_Store.Address address) + { + if (address == null) throw new ArgumentNullException(nameof(address)); + this.Address = address; + address.Opens.Add(this); + + Agents = new System.Collections.Generic.HashSet(); + Viewings = new System.Collections.Generic.HashSet(); + Init(); + } + + /// + /// Static create function (for use in LINQ queries, etc.) + /// + /// + public static Open Create(global::Ex5_Store.Address address) + { + return new Open(address); + } + + /************************************************************************* + * Properties + *************************************************************************/ + + /// + /// Identity, Indexed, Required + /// Unique identifier + /// + [Key] + [Required] + [System.ComponentModel.Description("Unique identifier")] + public long OpenId { get; set; } + + public DateTime? StartTime { get; set; } + + public int? Duration { get; set; } + + public string WelcomeMessage { get; set; } + + /// + /// Max length = 125 + /// + [MaxLength(125)] + [StringLength(125)] + public string Sync { get; set; } + + /************************************************************************* + * Navigation properties + *************************************************************************/ + + public virtual ICollection Agents { get; private set; } + + public virtual ICollection Viewings { get; private set; } + + /// + /// Required + /// + public virtual global::Ex5_Store.Address Address { get; set; } + + } +} + diff --git a/src/Examples/EF6/Ex5_Store/Generated/Person.generated.cs b/src/Examples/EF6/Ex5_Store/Generated/Person.generated.cs new file mode 100644 index 000000000..0432e9fcf --- /dev/null +++ b/src/Examples/EF6/Ex5_Store/Generated/Person.generated.cs @@ -0,0 +1,87 @@ +//------------------------------------------------------------------------------ +// +// This code was generated from a template. +// +// Manual changes to this file may cause unexpected behavior in your application. +// Manual changes to this file will be overwritten if the code is regenerated. +// +// Produced by Entity Framework Visual Editor v3.0.7.2 +// Source: https://github.com/msawczyn/EFDesigner +// Visual Studio Marketplace: https://marketplace.visualstudio.com/items?itemName=michaelsawczyn.EFDesigner +// Documentation: https://msawczyn.github.io/EFDesigner/ +// License (MIT): https://github.com/msawczyn/EFDesigner/blob/master/LICENSE +// +//------------------------------------------------------------------------------ + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using System.Linq; +using System.Runtime.CompilerServices; + +namespace Ex5_Store +{ + public partial class Person + { + partial void Init(); + + /// + /// Default constructor + /// + public Person() + { + Viewings = new System.Collections.Generic.HashSet(); + Tasks = new System.Collections.Generic.HashSet(); + + Init(); + } + + /************************************************************************* + * Properties + *************************************************************************/ + + /// + /// Identity, Indexed, Required + /// Unique identifier + /// + [Key] + [Required] + [System.ComponentModel.Description("Unique identifier")] + public long PeopleId { get; set; } + + public string FirstName { get; set; } + + public string LastName { get; set; } + + public string Email { get; set; } + + /// + /// Max length = 25 + /// + [MaxLength(25)] + [StringLength(25)] + public string Phone { get; set; } + + public string Notes { get; set; } + + /// + /// Max length = 125 + /// + [MaxLength(125)] + [StringLength(125)] + public string Sync { get; set; } + + /************************************************************************* + * Navigation properties + *************************************************************************/ + + public virtual ICollection Viewings { get; private set; } + + public virtual ICollection Tasks { get; private set; } + + } +} + diff --git a/src/Examples/EF6/Ex5_Store/Generated/PropertyStatus.generated.cs b/src/Examples/EF6/Ex5_Store/Generated/PropertyStatus.generated.cs new file mode 100644 index 000000000..d05d463d5 --- /dev/null +++ b/src/Examples/EF6/Ex5_Store/Generated/PropertyStatus.generated.cs @@ -0,0 +1,54 @@ +//------------------------------------------------------------------------------ +// +// This code was generated from a template. +// +// Manual changes to this file may cause unexpected behavior in your application. +// Manual changes to this file will be overwritten if the code is regenerated. +// +// Produced by Entity Framework Visual Editor v3.0.7.2 +// Source: https://github.com/msawczyn/EFDesigner +// Visual Studio Marketplace: https://marketplace.visualstudio.com/items?itemName=michaelsawczyn.EFDesigner +// Documentation: https://msawczyn.github.io/EFDesigner/ +// License (MIT): https://github.com/msawczyn/EFDesigner/blob/master/LICENSE +// +//------------------------------------------------------------------------------ + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using System.Linq; +using System.Runtime.CompilerServices; + +namespace Ex5_Store +{ + public partial class PropertyStatus + { + partial void Init(); + + /// + /// Default constructor + /// + public PropertyStatus() + { + Init(); + } + + /************************************************************************* + * Properties + *************************************************************************/ + + /// + /// Identity, Indexed, Required + /// Unique identifier + /// + [Key] + [Required] + [System.ComponentModel.Description("Unique identifier")] + public long Id { get; set; } + + } +} + diff --git a/src/Examples/EF6/Ex5_Store/Generated/PropertyType.generated.cs b/src/Examples/EF6/Ex5_Store/Generated/PropertyType.generated.cs new file mode 100644 index 000000000..ab508bf16 --- /dev/null +++ b/src/Examples/EF6/Ex5_Store/Generated/PropertyType.generated.cs @@ -0,0 +1,32 @@ +//------------------------------------------------------------------------------ +// +// This code was generated from a template. +// +// Manual changes to this file may cause unexpected behavior in your application. +// Manual changes to this file will be overwritten if the code is regenerated. +// +// Produced by Entity Framework Visual Editor v3.0.7.2 +// Source: https://github.com/msawczyn/EFDesigner +// Visual Studio Marketplace: https://marketplace.visualstudio.com/items?itemName=michaelsawczyn.EFDesigner +// Documentation: https://msawczyn.github.io/EFDesigner/ +// License (MIT): https://github.com/msawczyn/EFDesigner/blob/master/LICENSE +// +//------------------------------------------------------------------------------ + +using System; + +namespace Ex5_Store +{ + public enum PropertyType : Int32 + { + Unknown = -1, + Suburban_House = 1, + Apartment, + Townhouse, + Complex, + Land, + Rural_House, + Farm_and_House, + Farm + } +} diff --git a/src/Examples/EF6/Ex5_Store/Generated/RatingType.generated.cs b/src/Examples/EF6/Ex5_Store/Generated/RatingType.generated.cs new file mode 100644 index 000000000..ab2c9b0fc --- /dev/null +++ b/src/Examples/EF6/Ex5_Store/Generated/RatingType.generated.cs @@ -0,0 +1,34 @@ +//------------------------------------------------------------------------------ +// +// This code was generated from a template. +// +// Manual changes to this file may cause unexpected behavior in your application. +// Manual changes to this file will be overwritten if the code is regenerated. +// +// Produced by Entity Framework Visual Editor v3.0.7.2 +// Source: https://github.com/msawczyn/EFDesigner +// Visual Studio Marketplace: https://marketplace.visualstudio.com/items?itemName=michaelsawczyn.EFDesigner +// Documentation: https://msawczyn.github.io/EFDesigner/ +// License (MIT): https://github.com/msawczyn/EFDesigner/blob/master/LICENSE +// +//------------------------------------------------------------------------------ + +using System; + +namespace Ex5_Store +{ + public enum RatingType : Int32 + { + WouldNotRecommend_0 = 0, + Terrible_1 = 1, + Poor_2 = 2, + CouldDoBetter_3 = 3, + Ok_4 = 4, + Average_5 = 5, + Good_6 = 6, + VeryGood_7 = 7, + Excellent_8 = 8, + Exceptional_9 = 9, + Outstanding_10 = 10 + } +} diff --git a/src/Examples/EF6/Ex5_Store/Generated/ResultType.generated.cs b/src/Examples/EF6/Ex5_Store/Generated/ResultType.generated.cs new file mode 100644 index 000000000..e433c3bc9 --- /dev/null +++ b/src/Examples/EF6/Ex5_Store/Generated/ResultType.generated.cs @@ -0,0 +1,28 @@ +//------------------------------------------------------------------------------ +// +// This code was generated from a template. +// +// Manual changes to this file may cause unexpected behavior in your application. +// Manual changes to this file will be overwritten if the code is regenerated. +// +// Produced by Entity Framework Visual Editor v3.0.7.2 +// Source: https://github.com/msawczyn/EFDesigner +// Visual Studio Marketplace: https://marketplace.visualstudio.com/items?itemName=michaelsawczyn.EFDesigner +// Documentation: https://msawczyn.github.io/EFDesigner/ +// License (MIT): https://github.com/msawczyn/EFDesigner/blob/master/LICENSE +// +//------------------------------------------------------------------------------ + +using System; + +namespace Ex5_Store +{ + public enum ResultType : Int32 + { + Invalid, + Verified, + DontAnswer, + NotAvailable, + CorrectedWithoutCall + } +} diff --git a/src/Examples/EF6/Ex5_Store/Generated/Status.generated.cs b/src/Examples/EF6/Ex5_Store/Generated/Status.generated.cs new file mode 100644 index 000000000..e6d5b61de --- /dev/null +++ b/src/Examples/EF6/Ex5_Store/Generated/Status.generated.cs @@ -0,0 +1,26 @@ +//------------------------------------------------------------------------------ +// +// This code was generated from a template. +// +// Manual changes to this file may cause unexpected behavior in your application. +// Manual changes to this file will be overwritten if the code is regenerated. +// +// Produced by Entity Framework Visual Editor v3.0.7.2 +// Source: https://github.com/msawczyn/EFDesigner +// Visual Studio Marketplace: https://marketplace.visualstudio.com/items?itemName=michaelsawczyn.EFDesigner +// Documentation: https://msawczyn.github.io/EFDesigner/ +// License (MIT): https://github.com/msawczyn/EFDesigner/blob/master/LICENSE +// +//------------------------------------------------------------------------------ + +using System; + +namespace Ex5_Store +{ + public enum Status : Int32 + { + Listing, + Appraisal, + SoldByUs + } +} diff --git a/src/Examples/EF6/Ex5_Store/Generated/Tasks.generated.cs b/src/Examples/EF6/Ex5_Store/Generated/Tasks.generated.cs new file mode 100644 index 000000000..b22126c3a --- /dev/null +++ b/src/Examples/EF6/Ex5_Store/Generated/Tasks.generated.cs @@ -0,0 +1,109 @@ +//------------------------------------------------------------------------------ +// +// This code was generated from a template. +// +// Manual changes to this file may cause unexpected behavior in your application. +// Manual changes to this file will be overwritten if the code is regenerated. +// +// Produced by Entity Framework Visual Editor v3.0.7.2 +// Source: https://github.com/msawczyn/EFDesigner +// Visual Studio Marketplace: https://marketplace.visualstudio.com/items?itemName=michaelsawczyn.EFDesigner +// Documentation: https://msawczyn.github.io/EFDesigner/ +// License (MIT): https://github.com/msawczyn/EFDesigner/blob/master/LICENSE +// +//------------------------------------------------------------------------------ + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using System.Linq; +using System.Runtime.CompilerServices; + +namespace Ex5_Store +{ + public partial class Tasks + { + partial void Init(); + + /// + /// Default constructor. Protected due to required properties, but present because EF needs it. + /// + protected Tasks() + { + Audits = new System.Collections.Generic.HashSet(); + + Init(); + } + + /// + /// Replaces default constructor, since it's protected. Caller assumes responsibility for setting all required values before saving. + /// + public static Tasks CreateTasksUnsafe() + { + return new Tasks(); + } + + /// + /// Public constructor with required data + /// + /// + /// + public Tasks(global::Ex5_Store.Person person, global::Ex5_Store.Address address) + { + if (person == null) throw new ArgumentNullException(nameof(person)); + this.Person = person; + person.Tasks.Add(this); + + if (address == null) throw new ArgumentNullException(nameof(address)); + this.Address = address; + address.Tasks.Add(this); + + Audits = new System.Collections.Generic.HashSet(); + Init(); + } + + /// + /// Static create function (for use in LINQ queries, etc.) + /// + /// + /// + public static Tasks Create(global::Ex5_Store.Person person, global::Ex5_Store.Address address) + { + return new Tasks(person, address); + } + + /************************************************************************* + * Properties + *************************************************************************/ + + /// + /// Identity, Indexed, Required + /// Unique identifier + /// + [Key] + [Required] + [System.ComponentModel.Description("Unique identifier")] + public long Id { get; set; } + + /************************************************************************* + * Navigation properties + *************************************************************************/ + + public virtual ICollection Audits { get; private set; } + + /// + /// Required + /// + public virtual global::Ex5_Store.Person Person { get; set; } + + /// + /// Required + /// + public virtual global::Ex5_Store.Address Address { get; set; } + + } +} + diff --git a/src/Examples/EF6/Ex5_Store/Generated/Templates.generated.cs b/src/Examples/EF6/Ex5_Store/Generated/Templates.generated.cs new file mode 100644 index 000000000..e0ba9da84 --- /dev/null +++ b/src/Examples/EF6/Ex5_Store/Generated/Templates.generated.cs @@ -0,0 +1,54 @@ +//------------------------------------------------------------------------------ +// +// This code was generated from a template. +// +// Manual changes to this file may cause unexpected behavior in your application. +// Manual changes to this file will be overwritten if the code is regenerated. +// +// Produced by Entity Framework Visual Editor v3.0.7.2 +// Source: https://github.com/msawczyn/EFDesigner +// Visual Studio Marketplace: https://marketplace.visualstudio.com/items?itemName=michaelsawczyn.EFDesigner +// Documentation: https://msawczyn.github.io/EFDesigner/ +// License (MIT): https://github.com/msawczyn/EFDesigner/blob/master/LICENSE +// +//------------------------------------------------------------------------------ + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using System.Linq; +using System.Runtime.CompilerServices; + +namespace Ex5_Store +{ + public partial class Templates + { + partial void Init(); + + /// + /// Default constructor + /// + public Templates() + { + Init(); + } + + /************************************************************************* + * Properties + *************************************************************************/ + + /// + /// Identity, Indexed, Required + /// Unique identifier + /// + [Key] + [Required] + [System.ComponentModel.Description("Unique identifier")] + public long Id { get; set; } + + } +} + diff --git a/src/Examples/EF6/Ex5_Store/Generated/Viewing.generated.cs b/src/Examples/EF6/Ex5_Store/Generated/Viewing.generated.cs new file mode 100644 index 000000000..abf51b209 --- /dev/null +++ b/src/Examples/EF6/Ex5_Store/Generated/Viewing.generated.cs @@ -0,0 +1,117 @@ +//------------------------------------------------------------------------------ +// +// This code was generated from a template. +// +// Manual changes to this file may cause unexpected behavior in your application. +// Manual changes to this file will be overwritten if the code is regenerated. +// +// Produced by Entity Framework Visual Editor v3.0.7.2 +// Source: https://github.com/msawczyn/EFDesigner +// Visual Studio Marketplace: https://marketplace.visualstudio.com/items?itemName=michaelsawczyn.EFDesigner +// Documentation: https://msawczyn.github.io/EFDesigner/ +// License (MIT): https://github.com/msawczyn/EFDesigner/blob/master/LICENSE +// +//------------------------------------------------------------------------------ + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using System.Linq; +using System.Runtime.CompilerServices; + +namespace Ex5_Store +{ + public partial class Viewing + { + partial void Init(); + + /// + /// Default constructor. Protected due to required properties, but present because EF needs it. + /// + protected Viewing() + { + Init(); + } + + /// + /// Replaces default constructor, since it's protected. Caller assumes responsibility for setting all required values before saving. + /// + public static Viewing CreateViewingUnsafe() + { + return new Viewing(); + } + + /// + /// Public constructor with required data + /// + /// + /// + public Viewing(global::Ex5_Store.Open open, global::Ex5_Store.Person person) + { + if (open == null) throw new ArgumentNullException(nameof(open)); + this.Open = open; + open.Viewings.Add(this); + + if (person == null) throw new ArgumentNullException(nameof(person)); + this.Person = person; + person.Viewings.Add(this); + + Init(); + } + + /// + /// Static create function (for use in LINQ queries, etc.) + /// + /// + /// + public static Viewing Create(global::Ex5_Store.Open open, global::Ex5_Store.Person person) + { + return new Viewing(open, person); + } + + /************************************************************************* + * Properties + *************************************************************************/ + + /// + /// Identity, Indexed, Required + /// Unique identifier + /// + [Key] + [Required] + [System.ComponentModel.Description("Unique identifier")] + public long Id { get; set; } + + public DateTime? TimeIn { get; set; } + + public int? Guests { get; set; } + + public string Notes { get; set; } + + /// + /// Max length = 125 + /// + [MaxLength(125)] + [StringLength(125)] + public string Sync { get; set; } + + /************************************************************************* + * Navigation properties + *************************************************************************/ + + /// + /// Required + /// + public virtual global::Ex5_Store.Open Open { get; set; } + + /// + /// Required + /// + public virtual global::Ex5_Store.Person Person { get; set; } + + } +} + diff --git a/src/Examples/EF6/Ex5_Store/Program.cs b/src/Examples/EF6/Ex5_Store/Program.cs new file mode 100644 index 000000000..6cd056965 --- /dev/null +++ b/src/Examples/EF6/Ex5_Store/Program.cs @@ -0,0 +1,139 @@ +using System; +using System.Collections.Generic; +using System.Data.SqlClient; +using System.Diagnostics; +using System.Linq; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace Ex6_CRM +{ + static class Program + { + /// + /// The main entry point for the application. + /// + [STAThread] + static void Main() + { + Application.EnableVisualStyles(); + Application.SetCompatibleTextRenderingDefault(false); + + SetupLocalDb("mssqllocaldb", "RE_CRM"); + + Application.Run(new FrmEx6CRM()); + } + + + static void SetupLocalDb(string InstanceName = "mssqllocaldb", string DatabaseName = "EFVisualExamples") //This is a default instance name in local DB v13 + { + //Step 1: Islocaldb installed? + if (!CreateLocalDBInstance(InstanceName)) + { + + MessageBox.Show("CRITICAL ERROR: SqlLocalDb software is not installed!"); + + //Download SQL Server Express - LocalDB + // https://www.sqlshack.com/install-microsoft-sql-server-express-localdb/ + // https://www.microsoft.com/en-au/download/confirmation.aspx?id=101064 + // Microsoft SQL Server Express LocalDB supports silent installation. A user should download SqlLocalDB.msi and run the Command Prompt window as an administrator. Then, they should paste the following command: + // msiexec /i SqlLocalDB.msi /qn IACCEPTSQLLOCALDBLICENSETERMS = YES + string url = @"https://www.microsoft.com/en-au/download/confirmation.aspx?id=101064"; + Process.Start(url); + + Application.Exit(); + } + + //Step2: Create Database + + string connectionString = @"Data Source=(localdb)\" + InstanceName + $"; Integrated Security=True;"; + + if (!CheckDatabaseExists(connectionString, DatabaseName)) + { + //This is fixed -canot be changed + string UserPath = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); + + + SqlConnection connection = new SqlConnection(connectionString); + using (connection) + { + connection.Open(); + + string sql = $@" + CREATE DATABASE + {DatabaseName} + ON PRIMARY ( + NAME={DatabaseName}_data, + FILENAME = '{UserPath}\{DatabaseName}.mdf' + ) + LOG ON ( + NAME={DatabaseName}_log, + FILENAME = '{UserPath}\{DatabaseName}.ldf' + )"; + + SqlCommand command = new SqlCommand(sql, connection); + try + { + command.ExecuteNonQuery(); + } + catch (Exception ex) + { + MessageBox.Show($"CRITICAL ERROR: Database cannot be created\r\n{ex.ToString()}\r\nDoes Db exists in another instance?\r\n(Note: You cannot duplicate names across instances- requires unique name)"); + //You can debug using commandline + //>sqllocaldb info mssqllocaldb + + //https://docs.microsoft.com/en-us/sql/tools/sqllocaldb-utility?view=sql-server-ver15 + + string url = @"https://docs.microsoft.com/en-us/sql/relational-databases/express-localdb-instance-apis/command-line-management-tool-sqllocaldb-exe?view=sql-server-ver15"; + Process.Start(url); + + Application.Exit(); + } + + MessageBox.Show($" A New empty Local Database has been created successfully!\r\n\r\nSQLLOCALDB:{InstanceName}\r\nDATABASE:{DatabaseName}"); + } + } + } + + static bool CreateLocalDBInstance(string InstanceName) + { + // Lists all instances + // >sqllocaldb info + + // Start the child process. + Process p = new Process(); + // Redirect the output stream of the child process. + p.StartInfo.UseShellExecute = false; + p.StartInfo.RedirectStandardOutput = true; + p.StartInfo.FileName = "cmd.exe"; + p.StartInfo.Arguments = $"/C sqllocaldb c {InstanceName}"; //Create Local Db Instance + p.StartInfo.CreateNoWindow = true; + p.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; + p.Start(); + string sOutput = p.StandardOutput.ReadToEnd(); + p.WaitForExit(); + + //If LocalDb is not installed then it will return that 'sqllocaldb' is not recognized as an internal or external command operable program or batch file. + if (sOutput == null || sOutput.Trim().Length == 0 || sOutput.Contains("not recognized")) + return false; + if (sOutput.ToLower().Contains(InstanceName)) + return true; + return false; + } + + public static bool CheckDatabaseExists(string connectionString, string databaseName) + { + + using (var connection = new SqlConnection(connectionString)) + { + using (var command = new SqlCommand($"SELECT db_id('{databaseName}')", connection)) + { + connection.Open(); + var retval = command.ExecuteScalar(); + + return (retval != DBNull.Value); + } + } + } + } +} \ No newline at end of file diff --git a/src/Examples/EF6/Ex5_Store/Properties/AssemblyInfo.cs b/src/Examples/EF6/Ex5_Store/Properties/AssemblyInfo.cs new file mode 100644 index 000000000..fd11a0d81 --- /dev/null +++ b/src/Examples/EF6/Ex5_Store/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("Ex6_CRM")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("Ex6_CRM")] +[assembly: AssemblyCopyright("Copyright © 2021")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("9e4e33fd-1644-4ad1-9f6c-42389f7d3647")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/src/Examples/EF6/Ex5_Store/Properties/Resources.Designer.cs b/src/Examples/EF6/Ex5_Store/Properties/Resources.Designer.cs new file mode 100644 index 000000000..84b987903 --- /dev/null +++ b/src/Examples/EF6/Ex5_Store/Properties/Resources.Designer.cs @@ -0,0 +1,70 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + + +namespace Ex6_CRM.Properties +{ + /// + /// A strongly-typed resource class, for looking up localized strings, etc. + /// + // This class was auto-generated by the StronglyTypedResourceBuilder + // class via a tool like ResGen or Visual Studio. + // To add or remove a member, edit your .ResX file then rerun ResGen + // with the /str option, or rebuild your VS project. + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + internal class Resources + { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal Resources() + { + } + + /// + /// Returns the cached ResourceManager instance used by this class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Resources.ResourceManager ResourceManager + { + get + { + if ((resourceMan == null)) + { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Ex6_CRM.Properties.Resources", typeof(Resources).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// + /// Overrides the current thread's CurrentUICulture property for all + /// resource lookups using this strongly typed resource class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Globalization.CultureInfo Culture + { + get + { + return resourceCulture; + } + set + { + resourceCulture = value; + } + } + } +} diff --git a/src/Examples/EF6/Ex5_Store/Properties/Resources.resx b/src/Examples/EF6/Ex5_Store/Properties/Resources.resx new file mode 100644 index 000000000..af7dbebba --- /dev/null +++ b/src/Examples/EF6/Ex5_Store/Properties/Resources.resx @@ -0,0 +1,117 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/src/Examples/EF6/Ex5_Store/Properties/Settings.Designer.cs b/src/Examples/EF6/Ex5_Store/Properties/Settings.Designer.cs new file mode 100644 index 000000000..c49099766 --- /dev/null +++ b/src/Examples/EF6/Ex5_Store/Properties/Settings.Designer.cs @@ -0,0 +1,29 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + + +namespace Ex6_CRM.Properties +{ + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")] + internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase + { + + private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); + + public static Settings Default + { + get + { + return defaultInstance; + } + } + } +} diff --git a/src/Examples/EF6/Ex5_Store/Properties/Settings.settings b/src/Examples/EF6/Ex5_Store/Properties/Settings.settings new file mode 100644 index 000000000..39645652a --- /dev/null +++ b/src/Examples/EF6/Ex5_Store/Properties/Settings.settings @@ -0,0 +1,7 @@ + + + + + + + diff --git a/src/Examples/EF6/Ex6_Course/App.config b/src/Examples/EF6/Ex6_Course/App.config new file mode 100644 index 000000000..193aecc67 --- /dev/null +++ b/src/Examples/EF6/Ex6_Course/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/src/Examples/EF6/Ex6_Course/CourseManager.cs b/src/Examples/EF6/Ex6_Course/CourseManager.cs new file mode 100644 index 000000000..6153a7d78 --- /dev/null +++ b/src/Examples/EF6/Ex6_Course/CourseManager.cs @@ -0,0 +1 @@ + diff --git a/src/Examples/EF6/Ex6_Course/CourseManager.efmodel b/src/Examples/EF6/Ex6_Course/CourseManager.efmodel new file mode 100644 index 000000000..ec8445cda --- /dev/null +++ b/src/Examples/EF6/Ex6_Course/CourseManager.efmodel @@ -0,0 +1,52 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/Examples/EF6/Ex6_Course/CourseManager.efmodel.diagramx b/src/Examples/EF6/Ex6_Course/CourseManager.efmodel.diagramx new file mode 100644 index 000000000..869cf3f7e --- /dev/null +++ b/src/Examples/EF6/Ex6_Course/CourseManager.efmodel.diagramx @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/Examples/EF6/Ex6_Course/CourseManager.tt b/src/Examples/EF6/Ex6_Course/CourseManager.tt new file mode 100644 index 000000000..61c52a008 --- /dev/null +++ b/src/Examples/EF6/Ex6_Course/CourseManager.tt @@ -0,0 +1,74 @@ +<#@ template inherits="Microsoft.VisualStudio.TextTemplating.VSHost.ModelingTextTransformation" debug="true" + hostSpecific="true" language="C#" compilerOptions="/langversion:latest"#> +<#@ CleanupBehavior processor="T4VSHost" CleanupAfterProcessingtemplate="true" #> +<#@ assembly name="System.Data.Entity.Design.dll" +#><#@ assembly name="EnvDTE" +#><#@ include file="EFDesigner.ttinclude" once="true" +#><#@ output extension=".cs" +#><#@ import namespace="System.Linq" +#><#@ import namespace="System" +#><#@ import namespace="System.Data.Entity.Design.PluralizationServices" +#><#@ import namespace="System.Globalization" +#><#@ import namespace="Sawczyn.EFDesigner.EFModel" +#><#@ EFModel processor="EFModelDirectiveProcessor" requires="FileName='CourseManager.efmodel'" +#><# + Manager manager = Manager.Create(Host, GenerationEnvironment); + manager.FileNameMarker = ModelRoot.FileNameMarker; + + if (ModelRoot.Classes.Any()) + { + manager.StartHeader(false); + Output("//------------------------------------------------------------------------------"); + Output("// "); + Output("// This code was generated from a template."); + Output("//"); + Output("// Manual changes to this file may cause unexpected behavior in your application."); + Output("// Manual changes to this file will be overwritten if the code is regenerated."); + Output("//"); + Output("// Produced by Entity Framework Visual Editor v" + ModelRoot.DSLVersion); + Output("// Source: https://github.com/msawczyn/EFDesigner"); + Output("// Visual Studio Marketplace: https://marketplace.visualstudio.com/items?itemName=michaelsawczyn.EFDesigner"); + Output("// Documentation: https://msawczyn.github.io/EFDesigner/"); + Output("// License (MIT): https://github.com/msawczyn/EFDesigner/blob/master/LICENSE"); + Output("// "); + Output("//------------------------------------------------------------------------------"); + NL(); + + EFModelGenerator generator; + + switch (ModelRoot.EntityFrameworkVersion) + { + case EFVersion.EF6: + { + generator = new EF6ModelGenerator(this); + break; + } + + case EFVersion.EFCore: + { + switch ((int)ModelRoot.GetEntityFrameworkPackageVersionNum()) + { + case 2: + generator = new EFCore2ModelGenerator(this); + break; + + case 3: + generator = new EFCore3ModelGenerator(this); + break; + + default: + generator = new EFCore5ModelGenerator(this); + break; + } + break; + } + + default: + throw new InvalidOperationException("Unsupported Entity Framework version"); + } + + generator.Generate(manager); + } + + manager.Process(true); +#> \ No newline at end of file diff --git a/src/Examples/EF6/Ex6_Course/Ex5_Course.csproj b/src/Examples/EF6/Ex6_Course/Ex5_Course.csproj new file mode 100644 index 000000000..f87ba20d8 --- /dev/null +++ b/src/Examples/EF6/Ex6_Course/Ex5_Course.csproj @@ -0,0 +1,114 @@ + + + + + Debug + AnyCPU + {BF56F02E-DCEB-413D-8DE6-A1FFA71870A8} + WinExe + Ex5_Course + Ex5_Course + v4.8 + 512 + true + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + True + True + CourseManager.tt + + + Form + + + FrmCourseManager.cs + + + + + + + + + + + FrmCourseManager.cs + + + ResXFileCodeGenerator + Resources.Designer.cs + Designer + + + True + Resources.resx + True + + + + CourseManager.efmodel + + + SettingsSingleFileGenerator + Settings.Designer.cs + + + True + Settings.settings + True + + + + + + + + 6.4.4 + + + + + TextTemplatingFileGenerator + CourseManager.cs + + + + + + + + \ No newline at end of file diff --git a/src/Examples/EF6/Ex6_Course/FrmCourseManager.Designer.cs b/src/Examples/EF6/Ex6_Course/FrmCourseManager.Designer.cs new file mode 100644 index 000000000..45e5f4fc6 --- /dev/null +++ b/src/Examples/EF6/Ex6_Course/FrmCourseManager.Designer.cs @@ -0,0 +1,612 @@ + +namespace Ex5_Course +{ + partial class FrmCourseManager + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + this.txtDebug = new System.Windows.Forms.TextBox(); + this.label1 = new System.Windows.Forms.Label(); + this.txtConnection = new System.Windows.Forms.TextBox(); + this.groupBox1 = new System.Windows.Forms.GroupBox(); + this.lvStudents = new System.Windows.Forms.ListView(); + this.Id = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); + this.First = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); + this.Last = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); + this.btnUpdateStudent = new System.Windows.Forms.Button(); + this.btnDeleteStudent = new System.Windows.Forms.Button(); + this.btnNewStudent = new System.Windows.Forms.Button(); + this.label3 = new System.Windows.Forms.Label(); + this.label2 = new System.Windows.Forms.Label(); + this.txtLastname = new System.Windows.Forms.TextBox(); + this.txtFirstname = new System.Windows.Forms.TextBox(); + this.groupBox2 = new System.Windows.Forms.GroupBox(); + this.lvCourses = new System.Windows.Forms.ListView(); + this.ColId = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); + this.columnHeader1 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); + this.columnHeader2 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); + this.columnHeader3 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); + this.label10 = new System.Windows.Forms.Label(); + this.txtCourseID = new System.Windows.Forms.TextBox(); + this.btnUpdateCourse = new System.Windows.Forms.Button(); + this.btnDeletCourse = new System.Windows.Forms.Button(); + this.btnNewCourse = new System.Windows.Forms.Button(); + this.label4 = new System.Windows.Forms.Label(); + this.label5 = new System.Windows.Forms.Label(); + this.txtCredits = new System.Windows.Forms.TextBox(); + this.txtTitle = new System.Windows.Forms.TextBox(); + this.groupBox3 = new System.Windows.Forms.GroupBox(); + this.lvEnrolments = new System.Windows.Forms.ListView(); + this.columnHeader4 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); + this.columnHeader5 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); + this.columnHeader6 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); + this.columnHeader7 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); + this.btnEnrolmentUpdate = new System.Windows.Forms.Button(); + this.label9 = new System.Windows.Forms.Label(); + this.txtGrade = new System.Windows.Forms.TextBox(); + this.LblCourse = new System.Windows.Forms.Label(); + this.lblStudent = new System.Windows.Forms.Label(); + this.btnDeleteEnrol = new System.Windows.Forms.Button(); + this.btnNewEnrol = new System.Windows.Forms.Button(); + this.label6 = new System.Windows.Forms.Label(); + this.label7 = new System.Windows.Forms.Label(); + this.label8 = new System.Windows.Forms.Label(); + this.btnSeedData = new System.Windows.Forms.Button(); + this.groupBox1.SuspendLayout(); + this.groupBox2.SuspendLayout(); + this.groupBox3.SuspendLayout(); + this.SuspendLayout(); + // + // txtDebug + // + this.txtDebug.Location = new System.Drawing.Point(862, 49); + this.txtDebug.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + this.txtDebug.Multiline = true; + this.txtDebug.Name = "txtDebug"; + this.txtDebug.Size = new System.Drawing.Size(418, 742); + this.txtDebug.TabIndex = 15; + // + // label1 + // + this.label1.AutoSize = true; + this.label1.Location = new System.Drawing.Point(46, 29); + this.label1.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); + this.label1.Name = "label1"; + this.label1.Size = new System.Drawing.Size(167, 20); + this.label1.TabIndex = 14; + this.label1.Text = "Sql Server Connection"; + // + // txtConnection + // + this.txtConnection.Location = new System.Drawing.Point(46, 52); + this.txtConnection.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + this.txtConnection.Name = "txtConnection"; + this.txtConnection.Size = new System.Drawing.Size(734, 26); + this.txtConnection.TabIndex = 13; + this.txtConnection.Text = "..."; + // + // groupBox1 + // + this.groupBox1.Controls.Add(this.lvStudents); + this.groupBox1.Controls.Add(this.btnUpdateStudent); + this.groupBox1.Controls.Add(this.btnDeleteStudent); + this.groupBox1.Controls.Add(this.btnNewStudent); + this.groupBox1.Controls.Add(this.label3); + this.groupBox1.Controls.Add(this.label2); + this.groupBox1.Controls.Add(this.txtLastname); + this.groupBox1.Controls.Add(this.txtFirstname); + this.groupBox1.Location = new System.Drawing.Point(51, 88); + this.groupBox1.Name = "groupBox1"; + this.groupBox1.Size = new System.Drawing.Size(730, 192); + this.groupBox1.TabIndex = 16; + this.groupBox1.TabStop = false; + this.groupBox1.Text = "Student"; + // + // lvStudents + // + this.lvStudents.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { + this.Id, + this.First, + this.Last}); + this.lvStudents.FullRowSelect = true; + this.lvStudents.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.Nonclickable; + this.lvStudents.HideSelection = false; + this.lvStudents.Location = new System.Drawing.Point(12, 22); + this.lvStudents.Name = "lvStudents"; + this.lvStudents.Size = new System.Drawing.Size(445, 156); + this.lvStudents.TabIndex = 21; + this.lvStudents.UseCompatibleStateImageBehavior = false; + this.lvStudents.View = System.Windows.Forms.View.Details; + this.lvStudents.SelectedIndexChanged += new System.EventHandler(this.lvStudents_SelectedIndexChanged); + // + // Id + // + this.Id.Text = "Id"; + this.Id.Width = 30; + // + // First + // + this.First.Text = "First"; + this.First.Width = 150; + // + // Last + // + this.Last.Text = "Last"; + this.Last.Width = 200; + // + // btnUpdateStudent + // + this.btnUpdateStudent.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(0)))), ((int)(((byte)(192))))); + this.btnUpdateStudent.ForeColor = System.Drawing.Color.White; + this.btnUpdateStudent.Location = new System.Drawing.Point(628, 149); + this.btnUpdateStudent.Name = "btnUpdateStudent"; + this.btnUpdateStudent.Size = new System.Drawing.Size(75, 29); + this.btnUpdateStudent.TabIndex = 7; + this.btnUpdateStudent.Text = "Update"; + this.btnUpdateStudent.UseVisualStyleBackColor = false; + this.btnUpdateStudent.Click += new System.EventHandler(this.btnUpdateStudent_Click); + // + // btnDeleteStudent + // + this.btnDeleteStudent.BackColor = System.Drawing.Color.Red; + this.btnDeleteStudent.ForeColor = System.Drawing.Color.White; + this.btnDeleteStudent.Location = new System.Drawing.Point(548, 149); + this.btnDeleteStudent.Name = "btnDeleteStudent"; + this.btnDeleteStudent.Size = new System.Drawing.Size(75, 29); + this.btnDeleteStudent.TabIndex = 6; + this.btnDeleteStudent.Text = "Del"; + this.btnDeleteStudent.UseVisualStyleBackColor = false; + this.btnDeleteStudent.Click += new System.EventHandler(this.btnDeleteStudent_Click); + // + // btnNewStudent + // + this.btnNewStudent.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(192)))), ((int)(((byte)(0))))); + this.btnNewStudent.ForeColor = System.Drawing.Color.White; + this.btnNewStudent.Location = new System.Drawing.Point(466, 149); + this.btnNewStudent.Name = "btnNewStudent"; + this.btnNewStudent.Size = new System.Drawing.Size(75, 29); + this.btnNewStudent.TabIndex = 5; + this.btnNewStudent.Text = "New"; + this.btnNewStudent.UseVisualStyleBackColor = false; + this.btnNewStudent.Click += new System.EventHandler(this.btnNewStudent_Click); + // + // label3 + // + this.label3.AutoSize = true; + this.label3.Location = new System.Drawing.Point(464, 88); + this.label3.Name = "label3"; + this.label3.Size = new System.Drawing.Size(80, 20); + this.label3.TabIndex = 4; + this.label3.Text = "Lastname"; + // + // label2 + // + this.label2.AutoSize = true; + this.label2.Location = new System.Drawing.Point(464, 22); + this.label2.Name = "label2"; + this.label2.Size = new System.Drawing.Size(80, 20); + this.label2.TabIndex = 3; + this.label2.Text = "Firstname"; + // + // txtLastname + // + this.txtLastname.Location = new System.Drawing.Point(464, 111); + this.txtLastname.Name = "txtLastname"; + this.txtLastname.Size = new System.Drawing.Size(230, 26); + this.txtLastname.TabIndex = 2; + this.txtLastname.TextChanged += new System.EventHandler(this.txtLastname_TextChanged); + // + // txtFirstname + // + this.txtFirstname.Location = new System.Drawing.Point(464, 51); + this.txtFirstname.Name = "txtFirstname"; + this.txtFirstname.Size = new System.Drawing.Size(230, 26); + this.txtFirstname.TabIndex = 1; + this.txtFirstname.TextChanged += new System.EventHandler(this.txtFirstname_TextChanged); + // + // groupBox2 + // + this.groupBox2.Controls.Add(this.lvCourses); + this.groupBox2.Controls.Add(this.label10); + this.groupBox2.Controls.Add(this.txtCourseID); + this.groupBox2.Controls.Add(this.btnUpdateCourse); + this.groupBox2.Controls.Add(this.btnDeletCourse); + this.groupBox2.Controls.Add(this.btnNewCourse); + this.groupBox2.Controls.Add(this.label4); + this.groupBox2.Controls.Add(this.label5); + this.groupBox2.Controls.Add(this.txtCredits); + this.groupBox2.Controls.Add(this.txtTitle); + this.groupBox2.Location = new System.Drawing.Point(51, 298); + this.groupBox2.Name = "groupBox2"; + this.groupBox2.Size = new System.Drawing.Size(730, 192); + this.groupBox2.TabIndex = 17; + this.groupBox2.TabStop = false; + this.groupBox2.Text = "Course"; + // + // lvCourses + // + this.lvCourses.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { + this.ColId, + this.columnHeader1, + this.columnHeader2, + this.columnHeader3}); + this.lvCourses.FullRowSelect = true; + this.lvCourses.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.Nonclickable; + this.lvCourses.HideSelection = false; + this.lvCourses.Location = new System.Drawing.Point(12, 25); + this.lvCourses.Name = "lvCourses"; + this.lvCourses.Size = new System.Drawing.Size(445, 153); + this.lvCourses.TabIndex = 21; + this.lvCourses.UseCompatibleStateImageBehavior = false; + this.lvCourses.View = System.Windows.Forms.View.Details; + this.lvCourses.SelectedIndexChanged += new System.EventHandler(this.lvCourses_SelectedIndexChanged); + // + // ColId + // + this.ColId.Text = "Id"; + // + // columnHeader1 + // + this.columnHeader1.Text = "Course"; + this.columnHeader1.Width = 45; + // + // columnHeader2 + // + this.columnHeader2.Text = "Desc"; + this.columnHeader2.Width = 100; + // + // columnHeader3 + // + this.columnHeader3.Text = "Credits"; + this.columnHeader3.Width = 80; + // + // label10 + // + this.label10.AutoSize = true; + this.label10.Location = new System.Drawing.Point(608, 92); + this.label10.Name = "label10"; + this.label10.Size = new System.Drawing.Size(81, 20); + this.label10.TabIndex = 9; + this.label10.Text = "Course ID"; + // + // txtCourseID + // + this.txtCourseID.Location = new System.Drawing.Point(608, 115); + this.txtCourseID.Name = "txtCourseID"; + this.txtCourseID.Size = new System.Drawing.Size(79, 26); + this.txtCourseID.TabIndex = 8; + // + // btnUpdateCourse + // + this.btnUpdateCourse.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(0)))), ((int)(((byte)(192))))); + this.btnUpdateCourse.ForeColor = System.Drawing.Color.White; + this.btnUpdateCourse.Location = new System.Drawing.Point(628, 149); + this.btnUpdateCourse.Name = "btnUpdateCourse"; + this.btnUpdateCourse.Size = new System.Drawing.Size(75, 29); + this.btnUpdateCourse.TabIndex = 7; + this.btnUpdateCourse.Text = "Update"; + this.btnUpdateCourse.UseVisualStyleBackColor = false; + this.btnUpdateCourse.Click += new System.EventHandler(this.btnUpdateCourse_Click); + // + // btnDeletCourse + // + this.btnDeletCourse.BackColor = System.Drawing.Color.Red; + this.btnDeletCourse.ForeColor = System.Drawing.Color.White; + this.btnDeletCourse.Location = new System.Drawing.Point(548, 149); + this.btnDeletCourse.Name = "btnDeletCourse"; + this.btnDeletCourse.Size = new System.Drawing.Size(75, 29); + this.btnDeletCourse.TabIndex = 6; + this.btnDeletCourse.Text = "Del"; + this.btnDeletCourse.UseVisualStyleBackColor = false; + this.btnDeletCourse.Click += new System.EventHandler(this.btnDeletCourse_Click); + // + // btnNewCourse + // + this.btnNewCourse.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(192)))), ((int)(((byte)(0))))); + this.btnNewCourse.ForeColor = System.Drawing.Color.White; + this.btnNewCourse.Location = new System.Drawing.Point(466, 149); + this.btnNewCourse.Name = "btnNewCourse"; + this.btnNewCourse.Size = new System.Drawing.Size(75, 29); + this.btnNewCourse.TabIndex = 5; + this.btnNewCourse.Text = "New"; + this.btnNewCourse.UseVisualStyleBackColor = false; + this.btnNewCourse.Click += new System.EventHandler(this.btnNewCourse_Click); + // + // label4 + // + this.label4.AutoSize = true; + this.label4.Location = new System.Drawing.Point(464, 92); + this.label4.Name = "label4"; + this.label4.Size = new System.Drawing.Size(59, 20); + this.label4.TabIndex = 4; + this.label4.Text = "Credits"; + // + // label5 + // + this.label5.AutoSize = true; + this.label5.Location = new System.Drawing.Point(464, 26); + this.label5.Name = "label5"; + this.label5.Size = new System.Drawing.Size(38, 20); + this.label5.TabIndex = 3; + this.label5.Text = "Title"; + // + // txtCredits + // + this.txtCredits.Location = new System.Drawing.Point(464, 115); + this.txtCredits.Name = "txtCredits"; + this.txtCredits.Size = new System.Drawing.Size(79, 26); + this.txtCredits.TabIndex = 2; + // + // txtTitle + // + this.txtTitle.Location = new System.Drawing.Point(464, 55); + this.txtTitle.Name = "txtTitle"; + this.txtTitle.Size = new System.Drawing.Size(230, 26); + this.txtTitle.TabIndex = 1; + // + // groupBox3 + // + this.groupBox3.Controls.Add(this.lvEnrolments); + this.groupBox3.Controls.Add(this.btnEnrolmentUpdate); + this.groupBox3.Controls.Add(this.label9); + this.groupBox3.Controls.Add(this.txtGrade); + this.groupBox3.Controls.Add(this.LblCourse); + this.groupBox3.Controls.Add(this.lblStudent); + this.groupBox3.Controls.Add(this.btnDeleteEnrol); + this.groupBox3.Controls.Add(this.btnNewEnrol); + this.groupBox3.Controls.Add(this.label6); + this.groupBox3.Controls.Add(this.label7); + this.groupBox3.Location = new System.Drawing.Point(51, 512); + this.groupBox3.Name = "groupBox3"; + this.groupBox3.Size = new System.Drawing.Size(789, 282); + this.groupBox3.TabIndex = 18; + this.groupBox3.TabStop = false; + this.groupBox3.Text = "Enrolments - Link STUDENT with COURSE to ENROL and Record Grade"; + // + // lvEnrolments + // + this.lvEnrolments.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { + this.columnHeader4, + this.columnHeader5, + this.columnHeader6, + this.columnHeader7}); + this.lvEnrolments.FullRowSelect = true; + this.lvEnrolments.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.Nonclickable; + this.lvEnrolments.HideSelection = false; + this.lvEnrolments.Location = new System.Drawing.Point(76, 100); + this.lvEnrolments.Name = "lvEnrolments"; + this.lvEnrolments.Size = new System.Drawing.Size(624, 141); + this.lvEnrolments.TabIndex = 23; + this.lvEnrolments.UseCompatibleStateImageBehavior = false; + this.lvEnrolments.View = System.Windows.Forms.View.Details; + // + // columnHeader4 + // + this.columnHeader4.Text = "Id"; + this.columnHeader4.Width = 45; + // + // columnHeader5 + // + this.columnHeader5.Text = "Course"; + this.columnHeader5.Width = 100; + // + // columnHeader6 + // + this.columnHeader6.Text = "Student"; + this.columnHeader6.Width = 100; + // + // columnHeader7 + // + this.columnHeader7.Text = "Grade"; + this.columnHeader7.Width = 45; + // + // btnEnrolmentUpdate + // + this.btnEnrolmentUpdate.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(0)))), ((int)(((byte)(192))))); + this.btnEnrolmentUpdate.ForeColor = System.Drawing.Color.White; + this.btnEnrolmentUpdate.Location = new System.Drawing.Point(382, 249); + this.btnEnrolmentUpdate.Name = "btnEnrolmentUpdate"; + this.btnEnrolmentUpdate.Size = new System.Drawing.Size(103, 29); + this.btnEnrolmentUpdate.TabIndex = 11; + this.btnEnrolmentUpdate.Text = "Update"; + this.btnEnrolmentUpdate.UseVisualStyleBackColor = false; + this.btnEnrolmentUpdate.Click += new System.EventHandler(this.btnEnrolmentUpdate_Click); + // + // label9 + // + this.label9.AutoSize = true; + this.label9.Location = new System.Drawing.Point(130, 252); + this.label9.Name = "label9"; + this.label9.Size = new System.Drawing.Size(54, 20); + this.label9.TabIndex = 10; + this.label9.Text = "Grade"; + // + // txtGrade + // + this.txtGrade.Location = new System.Drawing.Point(200, 249); + this.txtGrade.Name = "txtGrade"; + this.txtGrade.Size = new System.Drawing.Size(150, 26); + this.txtGrade.TabIndex = 9; + // + // LblCourse + // + this.LblCourse.BackColor = System.Drawing.Color.White; + this.LblCourse.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; + this.LblCourse.Location = new System.Drawing.Point(472, 62); + this.LblCourse.Name = "LblCourse"; + this.LblCourse.Size = new System.Drawing.Size(226, 27); + this.LblCourse.TabIndex = 8; + // + // lblStudent + // + this.lblStudent.BackColor = System.Drawing.Color.White; + this.lblStudent.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; + this.lblStudent.Location = new System.Drawing.Point(70, 62); + this.lblStudent.Name = "lblStudent"; + this.lblStudent.Size = new System.Drawing.Size(294, 27); + this.lblStudent.TabIndex = 7; + // + // btnDeleteEnrol + // + this.btnDeleteEnrol.BackColor = System.Drawing.Color.Red; + this.btnDeleteEnrol.ForeColor = System.Drawing.Color.White; + this.btnDeleteEnrol.Location = new System.Drawing.Point(708, 211); + this.btnDeleteEnrol.Name = "btnDeleteEnrol"; + this.btnDeleteEnrol.Size = new System.Drawing.Size(75, 29); + this.btnDeleteEnrol.TabIndex = 6; + this.btnDeleteEnrol.Text = "Delete"; + this.btnDeleteEnrol.UseVisualStyleBackColor = false; + this.btnDeleteEnrol.Click += new System.EventHandler(this.btnDeleteEnrol_Click); + // + // btnNewEnrol + // + this.btnNewEnrol.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(192)))), ((int)(((byte)(0))))); + this.btnNewEnrol.ForeColor = System.Drawing.Color.White; + this.btnNewEnrol.Location = new System.Drawing.Point(382, 62); + this.btnNewEnrol.Name = "btnNewEnrol"; + this.btnNewEnrol.Size = new System.Drawing.Size(75, 29); + this.btnNewEnrol.TabIndex = 5; + this.btnNewEnrol.Text = "Enrol"; + this.btnNewEnrol.UseVisualStyleBackColor = false; + this.btnNewEnrol.Click += new System.EventHandler(this.btnNewEnrol_Click); + // + // label6 + // + this.label6.AutoSize = true; + this.label6.Location = new System.Drawing.Point(464, 32); + this.label6.Name = "label6"; + this.label6.Size = new System.Drawing.Size(223, 20); + this.label6.TabIndex = 4; + this.label6.Text = "Select Course from List Above"; + // + // label7 + // + this.label7.AutoSize = true; + this.label7.Location = new System.Drawing.Point(76, 32); + this.label7.Name = "label7"; + this.label7.Size = new System.Drawing.Size(193, 20); + this.label7.TabIndex = 3; + this.label7.Text = "Select Student List Above"; + // + // label8 + // + this.label8.AutoSize = true; + this.label8.Location = new System.Drawing.Point(870, 25); + this.label8.Name = "label8"; + this.label8.Size = new System.Drawing.Size(134, 20); + this.label8.TabIndex = 19; + this.label8.Text = "Debug messages"; + // + // btnSeedData + // + this.btnSeedData.Location = new System.Drawing.Point(536, 15); + this.btnSeedData.Name = "btnSeedData"; + this.btnSeedData.Size = new System.Drawing.Size(136, 32); + this.btnSeedData.TabIndex = 20; + this.btnSeedData.Text = "Seed Test Data"; + this.btnSeedData.UseVisualStyleBackColor = true; + this.btnSeedData.Click += new System.EventHandler(this.btnSeedData_Click); + // + // FrmCourseManager + // + this.AutoScaleDimensions = new System.Drawing.SizeF(9F, 20F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(1306, 805); + this.Controls.Add(this.btnSeedData); + this.Controls.Add(this.label8); + this.Controls.Add(this.groupBox3); + this.Controls.Add(this.groupBox2); + this.Controls.Add(this.groupBox1); + this.Controls.Add(this.txtDebug); + this.Controls.Add(this.label1); + this.Controls.Add(this.txtConnection); + this.Name = "FrmCourseManager"; + this.Text = "Course Manager"; + this.Load += new System.EventHandler(this.FrmCourseManager_Load); + this.groupBox1.ResumeLayout(false); + this.groupBox1.PerformLayout(); + this.groupBox2.ResumeLayout(false); + this.groupBox2.PerformLayout(); + this.groupBox3.ResumeLayout(false); + this.groupBox3.PerformLayout(); + this.ResumeLayout(false); + this.PerformLayout(); + + } + + #endregion + + private System.Windows.Forms.TextBox txtDebug; + private System.Windows.Forms.Label label1; + private System.Windows.Forms.TextBox txtConnection; + private System.Windows.Forms.GroupBox groupBox1; + private System.Windows.Forms.Button btnUpdateStudent; + private System.Windows.Forms.Button btnDeleteStudent; + private System.Windows.Forms.Button btnNewStudent; + private System.Windows.Forms.Label label3; + private System.Windows.Forms.Label label2; + private System.Windows.Forms.TextBox txtLastname; + private System.Windows.Forms.TextBox txtFirstname; + private System.Windows.Forms.GroupBox groupBox2; + private System.Windows.Forms.Button btnUpdateCourse; + private System.Windows.Forms.Button btnDeletCourse; + private System.Windows.Forms.Button btnNewCourse; + private System.Windows.Forms.Label label4; + private System.Windows.Forms.Label label5; + private System.Windows.Forms.TextBox txtCredits; + private System.Windows.Forms.TextBox txtTitle; + private System.Windows.Forms.GroupBox groupBox3; + private System.Windows.Forms.Label LblCourse; + private System.Windows.Forms.Label lblStudent; + private System.Windows.Forms.Button btnDeleteEnrol; + private System.Windows.Forms.Button btnNewEnrol; + private System.Windows.Forms.Label label6; + private System.Windows.Forms.Label label7; + private System.Windows.Forms.Label label8; + private System.Windows.Forms.Button btnEnrolmentUpdate; + private System.Windows.Forms.Label label9; + private System.Windows.Forms.TextBox txtGrade; + private System.Windows.Forms.Label label10; + private System.Windows.Forms.TextBox txtCourseID; + private System.Windows.Forms.Button btnSeedData; + private System.Windows.Forms.ListView lvStudents; + private System.Windows.Forms.ColumnHeader Id; + private System.Windows.Forms.ColumnHeader First; + private System.Windows.Forms.ColumnHeader Last; + private System.Windows.Forms.ListView lvCourses; + private System.Windows.Forms.ColumnHeader ColId; + private System.Windows.Forms.ColumnHeader columnHeader1; + private System.Windows.Forms.ColumnHeader columnHeader2; + private System.Windows.Forms.ColumnHeader columnHeader3; + private System.Windows.Forms.ListView lvEnrolments; + private System.Windows.Forms.ColumnHeader columnHeader4; + private System.Windows.Forms.ColumnHeader columnHeader5; + private System.Windows.Forms.ColumnHeader columnHeader6; + private System.Windows.Forms.ColumnHeader columnHeader7; + } +} + diff --git a/src/Examples/EF6/Ex6_Course/FrmCourseManager.cs b/src/Examples/EF6/Ex6_Course/FrmCourseManager.cs new file mode 100644 index 000000000..3ca5ee415 --- /dev/null +++ b/src/Examples/EF6/Ex6_Course/FrmCourseManager.cs @@ -0,0 +1,682 @@ +using System; +using System.Collections.Generic; +using System.Data.Entity; +using System.Data.Entity.Validation; +using System.Linq; +using System.Windows.Forms; + +namespace Ex5_Course +{ + public partial class FrmCourseManager : Form + { + public FrmCourseManager() + { + InitializeComponent(); + } + + public class Logger + { + //TO DO Show in text box on screen + + public static void Log(string message) + { + Console.WriteLine("EF Message: {0} ", message); + } + } + + private void FrmCourseManager_Load(object sender, EventArgs e) + { + using (CourseManager db = new CourseManager()) + { + db.Database.Log = Logger.Log; + + db.Database.Delete(); + txtDebug.Text += "Deleted DB\r\n"; + + db.Database.CreateIfNotExists(); + txtDebug.Text += "Created DB\r\n"; + + txtConnection.Text = db.Database.Connection.ConnectionString; + } + + SeedData(); + + DatabaseLoad_Enrolments(); + + DatabaseLoad_Students(); + DatabaseLoad_Courses(); + + } + + #region Student-CRUD + + private void lvStudents_SelectedIndexChanged(object sender, EventArgs e) + { + + if (lvStudents.SelectedItems.Count == 0) + { + lblStudent.Text = ""; + return; + } + + int selectedIndex = lvStudents.SelectedIndices[0]; + + ListViewItem lvItem = lvStudents.Items[selectedIndex]; + + string sPk = lvItem.SubItems[0].Text; + txtFirstname.Text = lvItem.SubItems[1].Text; + txtLastname.Text = lvItem.SubItems[2].Text; + + lblStudent.Text = sPk + ":" + txtFirstname.Text + " " + txtLastname.Text; + } + void DatabaseLoad_Students() + { + + lvStudents.Items.Clear(); + + using (CourseManager db = new CourseManager()) + { + db.Database.Log = Logger.Log; + + DbSet people = db.Students; + + foreach (Student p in people) + { + txtDebug.Text += String.Format("Loaded: {0} {1} {2} ", p.StudentId, p.FirstName, p.LastName) + "\r\n"; + + string[] row = { p.StudentId.ToString(), p.FirstName, p.LastName }; + ListViewItem listViewItem = new ListViewItem(row); + lvStudents.Items.Add(listViewItem); + } + } + } + + private void btnNewStudent_Click(object sender, EventArgs e) + { + + txtDebug.Text = "btnNewStudent_Click()\r\n"; + + using (CourseManager db = new CourseManager()) + { + db.Database.Log = Logger.Log; + + Student student = db.Students.Create(); + + student.FirstName = txtFirstname.Text; + student.LastName = txtLastname.Text; + + db.Students.Add(student); + + // This Exception handler helps to describe what went wrong with the EF database save. + // It decodes why the data did not comply with defined database field structure. e.g too long or wrong type. + try + { + db.SaveChanges(); + } + catch (System.Data.Entity.Validation.DbEntityValidationException dbEx) + { + Exception raise = dbEx; + foreach (DbEntityValidationResult validationErrors in dbEx.EntityValidationErrors) + { + foreach (DbValidationError validationError in validationErrors.ValidationErrors) + { + string message = string.Format("{0}:{1}", + validationErrors.Entry.Entity.ToString(), + validationError.ErrorMessage); + // raise a new exception nesting the current instance as InnerException + raise = new InvalidOperationException(message, raise); + } + } + throw raise; + } + } + DatabaseLoad_Students(); + } + private void btnDeleteStudent_Click(object sender, EventArgs e) + { + //Get StudentId from Listview + if (lvStudents.SelectedItems.Count == 0) + { + return; + } + + int selectedIndex = lvStudents.SelectedIndices[0]; + ListViewItem lvItem = lvStudents.Items[selectedIndex]; + string sPk = lvItem.SubItems[0].Text; + long pk = Convert.ToInt64(sPk); + + using (CourseManager db = new CourseManager()) + { + db.Database.Log = Logger.Log; + // Get student to delete + Student StudentToDelete = db.Students.First(s => s.StudentId == pk); + + if (StudentToDelete != null) + { + // Delete + db.Students.Remove(StudentToDelete); + db.SaveChanges(); + } + } + txtFirstname.Text = txtLastname.Text = ""; + DatabaseLoad_Students(); + } + + private void btnUpdateStudent_Click(object sender, EventArgs e) + { + //Get StudentId from Listview + if (lvStudents.SelectedItems.Count == 0) + { + return; + } + + int selectedIndex = lvStudents.SelectedIndices[0]; + ListViewItem lvItem = lvStudents.Items[selectedIndex]; + string sPk = lvItem.SubItems[0].Text; + long pk = Convert.ToInt64(sPk); + + using (CourseManager db = new CourseManager()) + { + db.Database.Log = Logger.Log; + + Student student = db.Students.SingleOrDefault(b => b.StudentId == pk); + if (student != null) + { + student.FirstName = txtFirstname.Text; + student.LastName = txtLastname.Text; + + db.SaveChanges(); + } + } + DatabaseLoad_Students(); + + } + #endregion + + #region Courses-CRUD + + private void lvCourses_SelectedIndexChanged(object sender, EventArgs e) + { + + if (lvCourses.SelectedItems.Count == 0) + { + LblCourse.Text = ""; + return; + } + + int selectedIndex = lvCourses.SelectedIndices[0]; + + ListViewItem lvItem = lvCourses.Items[selectedIndex]; + + string sPk = lvItem.SubItems[0].Text; + txtCourseID.Text = lvItem.SubItems[1].Text; + txtTitle.Text = lvItem.SubItems[2].Text; + txtCredits.Text = lvItem.SubItems[3].Text; + + LblCourse.Text = sPk + ":" + txtCourseID.Text + " " + txtTitle.Text; + } + + void DatabaseLoad_Courses() + { + + lvCourses.Items.Clear(); + + using (CourseManager db = new CourseManager()) + { + db.Database.Log = Logger.Log; + + DbSet courses = db.Courses; + + int count = courses.Count(); + + foreach (Course c in courses) + { + txtDebug.Text += String.Format("Course Loaded: {0} {1} {2} {3} ", c.CourseId, c.CourseLabel, c.Title, c.Credits) + "\r\n"; + + //Note: Could do tuple + string[] row = { c.CourseId.ToString(), c.CourseLabel, c.Title, c.Credits.ToString() }; + ListViewItem listViewItem = new ListViewItem(row); + lvCourses.Items.Add(listViewItem); + } + lvCourses.Refresh(); + } + + } + + private void btnNewCourse_Click(object sender, EventArgs e) + { + + txtDebug.Text = "btnNewCourse_Click()\r\n"; + + using (CourseManager db = new CourseManager()) + { + db.Database.Log = Logger.Log; + + Course course = db.Courses.Create(); + + course.CourseLabel = txtCourseID.Text; + course.Title = txtTitle.Text; + if (txtCredits.Text != "") + course.Credits = int.Parse(txtCredits.Text); + + db.Courses.Add(course); + + // This Exception handler helps to describe what went wrong with the EF database save. + // It decodes why the data did not comply with defined database field structure. e.g too long or wrong type. + try + { + db.SaveChanges(); + } + catch (System.Data.Entity.Validation.DbEntityValidationException dbEx) + { + Exception raise = dbEx; + foreach (DbEntityValidationResult validationErrors in dbEx.EntityValidationErrors) + { + foreach (DbValidationError validationError in validationErrors.ValidationErrors) + { + string message = string.Format("{0}:{1}", + validationErrors.Entry.Entity.ToString(), + validationError.ErrorMessage); + // raise a new exception nesting the current instance as InnerException + raise = new InvalidOperationException(message, raise); + } + } + throw raise; + } + } + + DatabaseLoad_Courses(); + } + + private void btnDeletCourse_Click(object sender, EventArgs e) + { + //Get PrimaryKey from Listview + if (lvCourses.SelectedItems.Count == 0) + { + return; + } + + int selectedIndex = lvCourses.SelectedIndices[0]; + ListViewItem lvItem = lvCourses.Items[selectedIndex]; + string sPk = lvItem.SubItems[0].Text; + long pk = Convert.ToInt64(sPk); + + using (CourseManager db = new CourseManager()) + { + db.Database.Log = Logger.Log; + // Get course to delete + Course CourseToDelete = db.Courses.First(c => c.CourseId == pk); + + if (CourseToDelete != null) + { + // Delete + db.Courses.Remove(CourseToDelete); + db.SaveChanges(); + } + } + + txtCourseID.Text = txtTitle.Text = txtCredits.Text = ""; + + DatabaseLoad_Courses(); + } + + private void btnUpdateCourse_Click(object sender, EventArgs e) + { + //Get PrimaryKey from Listview + if (lvCourses.SelectedItems.Count == 0) + { + return; + } + + int selectedIndex = lvCourses.SelectedIndices[0]; + ListViewItem lvItem = lvCourses.Items[selectedIndex]; + string sPk = lvItem.SubItems[0].Text; + long pk = Convert.ToInt64(sPk); + + using (CourseManager db = new CourseManager()) + { + db.Database.Log = Logger.Log; + // Get course to delete + Course CourseToUpdate = db.Courses.First(c => c.CourseId == pk); + + if (CourseToUpdate != null) + { + CourseToUpdate.CourseLabel = txtCourseID.Text; + CourseToUpdate.Title = txtTitle.Text; + if (txtCredits.Text != "") + CourseToUpdate.Credits = int.Parse(txtCredits.Text); + + db.SaveChanges(); + } + } + DatabaseLoad_Courses(); + } + + #endregion + + #region Enrollment-CRUD + private void btnNewEnrol_Click(object sender, EventArgs e) + { + txtDebug.Text = "btnNewEnrol_Click()\r\n"; + + //Get CourseId from Listview + if (lvCourses.SelectedItems.Count == 0) + { + return; + } + + int selectedIndex = lvCourses.SelectedIndices[0]; + ListViewItem lvItem = lvCourses.Items[selectedIndex]; + string sPk = lvItem.SubItems[0].Text; + long CoursePk = Convert.ToInt64(sPk); + + //Get StudentId from Listview + if (lvStudents.SelectedItems.Count == 0) + { + return; + } + + selectedIndex = lvStudents.SelectedIndices[0]; + lvItem = lvStudents.Items[selectedIndex]; + sPk = lvItem.SubItems[0].Text; + long StudentPk = Convert.ToInt64(sPk); + + using (CourseManager db = new CourseManager()) + { + db.Database.Log = Logger.Log; + + Enrollment enroll = db.Enrollments.Create(); + + if (txtGrade.Text != "") + enroll.Grade = Convert.ToInt32(txtGrade.Text); + + Course CourseToLink = db.Courses.First(c => c.CourseId == CoursePk); + Student StudentToLink = db.Students.First(s => s.StudentId == StudentPk); + + StudentToLink.Enrollments.Add(enroll); + CourseToLink.Enrollments.Add(enroll); + + db.Enrollments.Add(enroll); + + // This Exception handler helps to describe what went wrong with the EF database save. + // It decodes why the data did not comply with defined database field structure. e.g too long or wrong type. + try + { + db.SaveChanges(); + } + catch (System.Data.Entity.Validation.DbEntityValidationException dbEx) + { + Exception raise = dbEx; + foreach (DbEntityValidationResult validationErrors in dbEx.EntityValidationErrors) + { + foreach (DbValidationError validationError in validationErrors.ValidationErrors) + { + string message = string.Format("{0}:{1}", + validationErrors.Entry.Entity.ToString(), + validationError.ErrorMessage); + // raise a new exception nesting the current instance as InnerException + raise = new InvalidOperationException(message, raise); + } + } + throw raise; + } + } + + DatabaseLoad_Enrolments(); + + + } + private void btnEnrolmentUpdate_Click(object sender, EventArgs e) + { + txtDebug.Text = "btnEnrolmentUpdate_Click()\r\n"; + + //Get CourseId from Listview + if (lvEnrolments.SelectedItems.Count == 0) + { + txtDebug.Text = "NO Enrolment Selected? \r\n"; + return; + } + + int selectedIndex = lvEnrolments.SelectedIndices[0]; + ListViewItem lvItem = lvEnrolments.Items[selectedIndex]; + + + string sPk = lvItem.SubItems[0].Text; + long EnrolPk = Convert.ToInt64(sPk); + + using (CourseManager db = new CourseManager()) + { + + db.Database.Log = Logger.Log; + Enrollment EnrolToUpdate = db.Enrollments.First(en => en.EnrollmentId == EnrolPk); + + int grade = 0; + var isNumeric = int.TryParse(txtGrade.Text, out grade); + + if (isNumeric) + EnrolToUpdate.Grade = int.Parse(txtGrade.Text); + + //With Bidirectional Association you can access child objects via parent, e.g Course.Student etc + + //Changes work in linked tables + Student stu = EnrolToUpdate.Student; + stu.FirstName = "Albert"; + stu.LastName = "Einstein"; + + Course course = EnrolToUpdate.Course; + course.Title = "Relativity"; + + + // This Exception handler helps to describe what went wrong with the EF database save. + // It decodes why the data did not comply with defined database field structure. e.g too long or wrong type. + try + { + db.SaveChanges(); + } + catch (System.Data.Entity.Validation.DbEntityValidationException dbEx) + { + Exception raise = dbEx; + foreach (DbEntityValidationResult validationErrors in dbEx.EntityValidationErrors) + { + foreach (DbValidationError validationError in validationErrors.ValidationErrors) + { + string message = string.Format("{0}:{1}", + validationErrors.Entry.Entity.ToString(), + validationError.ErrorMessage); + // raise a new exception nesting the current instance as InnerException + raise = new InvalidOperationException(message, raise); + } + } + throw raise; + } + } + + DatabaseLoad_Enrolments(); + } + + private void btnDeleteEnrol_Click(object sender, EventArgs e) + { + //Get PrimaryKey from Listview + if (lvEnrolments.SelectedItems.Count == 0) + { + txtDebug.Text = "Cannot delete, NO Enrolment Selected ? \r\n"; + return; + } + + int selectedIndex = lvEnrolments.SelectedIndices[0]; + ListViewItem lvItem = lvEnrolments.Items[selectedIndex]; + string sPk = lvItem.SubItems[0].Text; + long pk = Convert.ToInt64(sPk); + + using (CourseManager db = new CourseManager()) + { + db.Database.Log = Logger.Log; + // Get course to delete + Enrollment EnrolToDelete = db.Enrollments.First(en => en.EnrollmentId == pk); + + if (EnrolToDelete != null) + { + // Delete + db.Enrollments.Remove(EnrolToDelete); + db.SaveChanges(); + } + } + + txtGrade.Text = ""; + + DatabaseLoad_Enrolments(); + } + + void DatabaseLoad_Enrolments() + { + lvEnrolments.Items.Clear(); + + using (CourseManager db = new CourseManager()) + { + db.Database.Log = Logger.Log; + + DbSet enrolments = db.Enrollments; + + foreach (Enrollment en in enrolments) + { + string StudentName = ""; + string CourseTitle = ""; + + /* + //If you get already an open datareader error? + + //Simply include "MultipleActiveResultSets=true" in your connection string + + It is not about closing connection. EF manages connection correctly. + My understanding of this problem is that there are multiple data retrieval commands executed on single connection + (or single command with multiple selects) while next DataReader is executed before first one has completed the reading. + The only way to avoid the exception is to allow multiple nested DataReaders = turn on MultipleActiveResultSets. + Another scenario when this always happens is when you iterate through result of the query (IQueryable) + and you will trigger lazy loading for loaded entity inside the iteration. + + */ + + Course course = en.Course; + + if (course != null) + CourseTitle = course.Title; + + Student stu = en.Student; + + if (stu != null) + StudentName = stu.FirstName + " " + stu.LastName; + + txtDebug.Text += String.Format("Loaded: {0} {1} {2} {3} ", en.EnrollmentId, CourseTitle, StudentName, en.Grade.ToString());//; e.EnrollmentId, e.EnrollmentId);// + "\r\n"; + + string[] row = { en.EnrollmentId.ToString(), CourseTitle, StudentName, en.Grade.ToString() }; + + ListViewItem listViewItem = new ListViewItem(row); + lvEnrolments.Items.Add(listViewItem); + } + } + } + + + #endregion + + + #region GUIActions + + private void LbCourses_SelectedIndexChanged(object sender, EventArgs e) + { + //Get Record and Fill Textboxes + + } + + + private void txtFirstname_TextChanged(object sender, EventArgs e) + { + //Show Add + } + + + private void txtLastname_TextChanged(object sender, EventArgs e) + { + + } + #endregion + + + #region SeedDb + void SeedData() + { + using (CourseManager db = new CourseManager()) + { + List students = new List + { + new Student{FirstName="Carson",LastName="Alexander" },//,EnrollmentDate=DateTime.Parse("2005-09-01")}, + new Student{FirstName="Meredith",LastName="Alonso"},//EnrollmentDate=DateTime.Parse("2002-09-01")}, + new Student{FirstName="Arturo",LastName="Anand"},//EnrollmentDate=DateTime.Parse("2003-09-01")}, + new Student{FirstName="Gytis",LastName="Barzdukas"},//EnrollmentDate=DateTime.Parse("2002-09-01")}, + new Student{FirstName="Yan",LastName="Li"},//EnrollmentDate=DateTime.Parse("2002-09-01")}, + new Student{FirstName="Peggy",LastName="Justice"},//EnrollmentDate=DateTime.Parse("2001-09-01")}, + new Student{FirstName="Laura",LastName="Norman"},//EnrollmentDate=DateTime.Parse("2003-09-01")}, + new Student{FirstName="Nino",LastName="Olivetto"}//EnrollmentDate=DateTime.Parse("2005-09-01")} + }; + + //This does not work + //students.ForEach(s => db.Students.Add(s)); + + //Have to use create? Dont know why? + foreach (Student s in students) + { + Student stu = db.Students.Create(); + stu.FirstName = s.FirstName; + stu.LastName = s.LastName; + + db.Students.Add(stu); + } + + //Duplicate Key added? + + db.SaveChanges(); + + List courses = new List + { + new Course{CourseLabel="1050",Title="Chemistry",Credits=3,}, + new Course{CourseLabel="4022",Title="Microeconomics",Credits=3,}, + new Course{CourseLabel="4041",Title="Macroeconomics",Credits=3,}, + new Course{CourseLabel="1045",Title="Calculus",Credits=4,}, + new Course{CourseLabel="3141",Title="Trigonometry",Credits=4,}, + new Course{CourseLabel="2021",Title="Composition",Credits=3,}, + new Course{CourseLabel="2042",Title="Literature",Credits=4,} + }; + + //This does not work + //courses.ForEach(s => db.Courses.Add(s)); + + //Have to use create? Dont know why? + foreach (Course c in courses) + { + Course course = db.Courses.Create(); + course.CourseLabel = c.CourseLabel; + course.Title = c.Title; + course.Credits = c.Credits; + + db.Courses.Add(course); + } + + db.SaveChanges(); + } + + DatabaseLoad_Students(); + DatabaseLoad_Courses(); + } + + #endregion + + private void btnSeedData_Click(object sender, EventArgs e) + { + + SeedData(); + + } + + + } +} \ No newline at end of file diff --git a/src/Examples/EF6/Ex6_Course/FrmCourseManager.resx b/src/Examples/EF6/Ex6_Course/FrmCourseManager.resx new file mode 100644 index 000000000..1af7de150 --- /dev/null +++ b/src/Examples/EF6/Ex6_Course/FrmCourseManager.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/src/Examples/EF6/Ex6_Course/Generated/Course.generated.cs b/src/Examples/EF6/Ex6_Course/Generated/Course.generated.cs new file mode 100644 index 000000000..108ac9551 --- /dev/null +++ b/src/Examples/EF6/Ex6_Course/Generated/Course.generated.cs @@ -0,0 +1,71 @@ +//------------------------------------------------------------------------------ +// +// This code was generated from a template. +// +// Manual changes to this file may cause unexpected behavior in your application. +// Manual changes to this file will be overwritten if the code is regenerated. +// +// Produced by Entity Framework Visual Editor v3.0.7.2 +// Source: https://github.com/msawczyn/EFDesigner +// Visual Studio Marketplace: https://marketplace.visualstudio.com/items?itemName=michaelsawczyn.EFDesigner +// Documentation: https://msawczyn.github.io/EFDesigner/ +// License (MIT): https://github.com/msawczyn/EFDesigner/blob/master/LICENSE +// +//------------------------------------------------------------------------------ + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using System.Linq; +using System.Runtime.CompilerServices; + +namespace Ex5_Course +{ + public partial class Course + { + partial void Init(); + + /// + /// Default constructor + /// + public Course() + { + Enrollments = new System.Collections.Generic.HashSet(); + + Init(); + } + + /************************************************************************* + * Properties + *************************************************************************/ + + /// + /// Identity, Required + /// + [Key] + [Required] + public long CourseId { get; set; } + + /// + /// Max length = 25 + /// + [MaxLength(25)] + [StringLength(25)] + public string CourseLabel { get; set; } + + public string Title { get; set; } + + public int? Credits { get; set; } + + /************************************************************************* + * Navigation properties + *************************************************************************/ + + public virtual ICollection Enrollments { get; private set; } + + } +} + diff --git a/src/Examples/EF6/Ex6_Course/Generated/CourseManager.generated.cs b/src/Examples/EF6/Ex6_Course/Generated/CourseManager.generated.cs new file mode 100644 index 000000000..c5ac4051e --- /dev/null +++ b/src/Examples/EF6/Ex6_Course/Generated/CourseManager.generated.cs @@ -0,0 +1,156 @@ +//------------------------------------------------------------------------------ +// +// This code was generated from a template. +// +// Manual changes to this file may cause unexpected behavior in your application. +// Manual changes to this file will be overwritten if the code is regenerated. +// +// Produced by Entity Framework Visual Editor v3.0.7.2 +// Source: https://github.com/msawczyn/EFDesigner +// Visual Studio Marketplace: https://marketplace.visualstudio.com/items?itemName=michaelsawczyn.EFDesigner +// Documentation: https://msawczyn.github.io/EFDesigner/ +// License (MIT): https://github.com/msawczyn/EFDesigner/blob/master/LICENSE +// +//------------------------------------------------------------------------------ + +using System; +using System.Collections.Generic; +using System.Linq; +using System.ComponentModel.DataAnnotations.Schema; +using System.Data.Entity; +using System.Data.Entity.Infrastructure.Annotations; + +namespace Ex5_Course +{ + /// + public partial class CourseManager : DbContext + { + #region DbSets + public virtual System.Data.Entity.DbSet Courses { get; set; } + public virtual System.Data.Entity.DbSet Enrollments { get; set; } + public virtual System.Data.Entity.DbSet Students { get; set; } + #endregion DbSets + + #region Constructors + + partial void CustomInit(); + + /// + /// Default connection string + /// + public static string ConnectionString { get; set; } = @"Data Source=(localdb)\mssqllocaldb;Initial Catalog=EFVisualExamples;MultipleActiveResultSets=true;Integrated Security=True"; + /// + public CourseManager() : base(ConnectionString) + { + Configuration.LazyLoadingEnabled = true; + Configuration.ProxyCreationEnabled = true; + System.Data.Entity.Database.SetInitializer(new CourseManagerDatabaseInitializer()); + CustomInit(); + } + + /// + public CourseManager(string connectionString) : base(connectionString) + { + Configuration.LazyLoadingEnabled = true; + Configuration.ProxyCreationEnabled = true; + System.Data.Entity.Database.SetInitializer(new CourseManagerDatabaseInitializer()); + CustomInit(); + } + + /// + public CourseManager(string connectionString, System.Data.Entity.Infrastructure.DbCompiledModel model) : base(connectionString, model) + { + Configuration.LazyLoadingEnabled = true; + Configuration.ProxyCreationEnabled = true; + System.Data.Entity.Database.SetInitializer(new CourseManagerDatabaseInitializer()); + CustomInit(); + } + + /// + public CourseManager(System.Data.Common.DbConnection existingConnection, bool contextOwnsConnection) : base(existingConnection, contextOwnsConnection) + { + Configuration.LazyLoadingEnabled = true; + Configuration.ProxyCreationEnabled = true; + System.Data.Entity.Database.SetInitializer(new CourseManagerDatabaseInitializer()); + CustomInit(); + } + + /// + public CourseManager(System.Data.Common.DbConnection existingConnection, System.Data.Entity.Infrastructure.DbCompiledModel model, bool contextOwnsConnection) : base(existingConnection, model, contextOwnsConnection) + { + Configuration.LazyLoadingEnabled = true; + Configuration.ProxyCreationEnabled = true; + System.Data.Entity.Database.SetInitializer(new CourseManagerDatabaseInitializer()); + CustomInit(); + } + + /// + public CourseManager(System.Data.Entity.Infrastructure.DbCompiledModel model) : base(model) + { + Configuration.LazyLoadingEnabled = true; + Configuration.ProxyCreationEnabled = true; + System.Data.Entity.Database.SetInitializer(new CourseManagerDatabaseInitializer()); + CustomInit(); + } + + /// + public CourseManager(System.Data.Entity.Core.Objects.ObjectContext objectContext, bool dbContextOwnsObjectContext) : base(objectContext, dbContextOwnsObjectContext) + { + Configuration.LazyLoadingEnabled = true; + Configuration.ProxyCreationEnabled = true; + System.Data.Entity.Database.SetInitializer(new CourseManagerDatabaseInitializer()); + CustomInit(); + } + + #endregion Constructors + + partial void OnModelCreatingImpl(System.Data.Entity.DbModelBuilder modelBuilder); + partial void OnModelCreatedImpl(System.Data.Entity.DbModelBuilder modelBuilder); + + /// + protected override void OnModelCreating(System.Data.Entity.DbModelBuilder modelBuilder) + { + base.OnModelCreating(modelBuilder); + OnModelCreatingImpl(modelBuilder); + + modelBuilder.HasDefaultSchema("dbo"); + + modelBuilder.Entity() + .ToTable("Courses") + .HasKey(t => t.CourseId); + modelBuilder.Entity() + .Property(t => t.CourseId) + .IsRequired() + .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity); + modelBuilder.Entity() + .Property(t => t.CourseLabel) + .HasMaxLength(25); + + modelBuilder.Entity() + .ToTable("Enrollments") + .HasKey(t => t.EnrollmentId); + modelBuilder.Entity() + .Property(t => t.EnrollmentId) + .IsRequired() + .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity); + modelBuilder.Entity() + .HasRequired(x => x.Course) + .WithMany(x => x.Enrollments) + .Map(x => x.MapKey("CourseCourseId")); + modelBuilder.Entity() + .HasRequired(x => x.Student) + .WithMany(x => x.Enrollments) + .Map(x => x.MapKey("StudentStudentId")); + + modelBuilder.Entity() + .ToTable("Students") + .HasKey(t => t.StudentId); + modelBuilder.Entity() + .Property(t => t.StudentId) + .IsRequired() + .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity); + + OnModelCreatedImpl(modelBuilder); + } + } +} diff --git a/src/Examples/EF6/Ex6_Course/Generated/CourseManagerDatabaseInitializer.generated.cs b/src/Examples/EF6/Ex6_Course/Generated/CourseManagerDatabaseInitializer.generated.cs new file mode 100644 index 000000000..bbf9f4792 --- /dev/null +++ b/src/Examples/EF6/Ex6_Course/Generated/CourseManagerDatabaseInitializer.generated.cs @@ -0,0 +1,24 @@ +//------------------------------------------------------------------------------ +// +// This code was generated from a template. +// +// Manual changes to this file may cause unexpected behavior in your application. +// Manual changes to this file will be overwritten if the code is regenerated. +// +// Produced by Entity Framework Visual Editor v3.0.7.2 +// Source: https://github.com/msawczyn/EFDesigner +// Visual Studio Marketplace: https://marketplace.visualstudio.com/items?itemName=michaelsawczyn.EFDesigner +// Documentation: https://msawczyn.github.io/EFDesigner/ +// License (MIT): https://github.com/msawczyn/EFDesigner/blob/master/LICENSE +// +//------------------------------------------------------------------------------ + +using System.Data.Entity; + +namespace Ex5_Course +{ + /// + public partial class CourseManagerDatabaseInitializer : DropCreateDatabaseIfModelChanges + { + } +} diff --git a/src/Examples/EF6/Ex6_Course/Generated/CourseManagerDbMigrationConfiguration.generated.cs b/src/Examples/EF6/Ex6_Course/Generated/CourseManagerDbMigrationConfiguration.generated.cs new file mode 100644 index 000000000..0390bf3d9 --- /dev/null +++ b/src/Examples/EF6/Ex6_Course/Generated/CourseManagerDbMigrationConfiguration.generated.cs @@ -0,0 +1,33 @@ +//------------------------------------------------------------------------------ +// +// This code was generated from a template. +// +// Manual changes to this file may cause unexpected behavior in your application. +// Manual changes to this file will be overwritten if the code is regenerated. +// +// Produced by Entity Framework Visual Editor v3.0.7.2 +// Source: https://github.com/msawczyn/EFDesigner +// Visual Studio Marketplace: https://marketplace.visualstudio.com/items?itemName=michaelsawczyn.EFDesigner +// Documentation: https://msawczyn.github.io/EFDesigner/ +// License (MIT): https://github.com/msawczyn/EFDesigner/blob/master/LICENSE +// +//------------------------------------------------------------------------------ + +using System.Data.Entity.Migrations; + +namespace Migrations +{ + /// + public sealed partial class CourseManagerDbMigrationConfiguration : DbMigrationsConfiguration + { + partial void Init(); + + /// + public CourseManagerDbMigrationConfiguration() + { + AutomaticMigrationsEnabled = true; + AutomaticMigrationDataLossAllowed = false; + Init(); + } + } +} diff --git a/src/Examples/EF6/Ex6_Course/Generated/Enrollment.generated.cs b/src/Examples/EF6/Ex6_Course/Generated/Enrollment.generated.cs new file mode 100644 index 000000000..11ce66d38 --- /dev/null +++ b/src/Examples/EF6/Ex6_Course/Generated/Enrollment.generated.cs @@ -0,0 +1,104 @@ +//------------------------------------------------------------------------------ +// +// This code was generated from a template. +// +// Manual changes to this file may cause unexpected behavior in your application. +// Manual changes to this file will be overwritten if the code is regenerated. +// +// Produced by Entity Framework Visual Editor v3.0.7.2 +// Source: https://github.com/msawczyn/EFDesigner +// Visual Studio Marketplace: https://marketplace.visualstudio.com/items?itemName=michaelsawczyn.EFDesigner +// Documentation: https://msawczyn.github.io/EFDesigner/ +// License (MIT): https://github.com/msawczyn/EFDesigner/blob/master/LICENSE +// +//------------------------------------------------------------------------------ + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using System.Linq; +using System.Runtime.CompilerServices; + +namespace Ex5_Course +{ + public partial class Enrollment + { + partial void Init(); + + /// + /// Default constructor. Protected due to required properties, but present because EF needs it. + /// + protected Enrollment() + { + Init(); + } + + /// + /// Replaces default constructor, since it's protected. Caller assumes responsibility for setting all required values before saving. + /// + public static Enrollment CreateEnrollmentUnsafe() + { + return new Enrollment(); + } + + /// + /// Public constructor with required data + /// + /// + /// + public Enrollment(global::Ex5_Course.Course course, global::Ex5_Course.Student student) + { + if (course == null) throw new ArgumentNullException(nameof(course)); + this.Course = course; + course.Enrollments.Add(this); + + if (student == null) throw new ArgumentNullException(nameof(student)); + this.Student = student; + student.Enrollments.Add(this); + + Init(); + } + + /// + /// Static create function (for use in LINQ queries, etc.) + /// + /// + /// + public static Enrollment Create(global::Ex5_Course.Course course, global::Ex5_Course.Student student) + { + return new Enrollment(course, student); + } + + /************************************************************************* + * Properties + *************************************************************************/ + + /// + /// Identity, Required + /// + [Key] + [Required] + public long EnrollmentId { get; set; } + + public int? Grade { get; set; } + + /************************************************************************* + * Navigation properties + *************************************************************************/ + + /// + /// Required + /// + public virtual global::Ex5_Course.Course Course { get; set; } + + /// + /// Required + /// + public virtual global::Ex5_Course.Student Student { get; set; } + + } +} + diff --git a/src/Examples/EF6/Ex6_Course/Generated/Student.generated.cs b/src/Examples/EF6/Ex6_Course/Generated/Student.generated.cs new file mode 100644 index 000000000..87353da37 --- /dev/null +++ b/src/Examples/EF6/Ex6_Course/Generated/Student.generated.cs @@ -0,0 +1,64 @@ +//------------------------------------------------------------------------------ +// +// This code was generated from a template. +// +// Manual changes to this file may cause unexpected behavior in your application. +// Manual changes to this file will be overwritten if the code is regenerated. +// +// Produced by Entity Framework Visual Editor v3.0.7.2 +// Source: https://github.com/msawczyn/EFDesigner +// Visual Studio Marketplace: https://marketplace.visualstudio.com/items?itemName=michaelsawczyn.EFDesigner +// Documentation: https://msawczyn.github.io/EFDesigner/ +// License (MIT): https://github.com/msawczyn/EFDesigner/blob/master/LICENSE +// +//------------------------------------------------------------------------------ + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using System.Linq; +using System.Runtime.CompilerServices; + +namespace Ex5_Course +{ + public partial class Student + { + partial void Init(); + + /// + /// Default constructor + /// + public Student() + { + Enrollments = new System.Collections.Generic.HashSet(); + + Init(); + } + + /************************************************************************* + * Properties + *************************************************************************/ + + /// + /// Identity, Indexed, Required + /// + [Key] + [Required] + public long StudentId { get; set; } + + public string FirstName { get; set; } + + public string LastName { get; set; } + + /************************************************************************* + * Navigation properties + *************************************************************************/ + + public virtual ICollection Enrollments { get; private set; } + + } +} + diff --git a/src/Examples/EF6/Ex6_Course/Program.cs b/src/Examples/EF6/Ex6_Course/Program.cs new file mode 100644 index 000000000..eddbe53f7 --- /dev/null +++ b/src/Examples/EF6/Ex6_Course/Program.cs @@ -0,0 +1,144 @@ +using System; +using System.Collections.Generic; +using System.Data.SqlClient; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace Ex5_Course +{ + static class Program + { + /// + /// The main entry point for the application. + /// + [STAThread] + static void Main() + { + Application.EnableVisualStyles(); + Application.SetCompatibleTextRenderingDefault(false); + + //Data Source=(localdb)\mssqllocaldb;Initial Catalog=EFVisualExamples;MultipleActiveResultSets=true;Integrated Security=True + //Match Connection string in .efmodel + + SetupLocalDb("mssqllocaldb", "EFVisualExamples"); + + Application.Run(new FrmCourseManager()); + + } + + + static void SetupLocalDb(string InstanceName = "mssqllocaldb", string DatabaseName = "EFVisualExamples") //This is a default instance name in local DB v13 + { + //Step 1: Islocaldb installed? + if (!CreateLocalDBInstance(InstanceName)) + { + + MessageBox.Show("CRITICAL ERROR: SqlLocalDb software is not installed!"); + + //Download SQL Server Express - LocalDB + // https://www.sqlshack.com/install-microsoft-sql-server-express-localdb/ + // https://www.microsoft.com/en-au/download/confirmation.aspx?id=101064 + // Microsoft SQL Server Express LocalDB supports silent installation. A user should download SqlLocalDB.msi and run the Command Prompt window as an administrator. Then, they should paste the following command: + // msiexec /i SqlLocalDB.msi /qn IACCEPTSQLLOCALDBLICENSETERMS = YES + string url = @"https://www.microsoft.com/en-au/download/confirmation.aspx?id=101064"; + Process.Start(url); + + Application.Exit(); + } + + //Step2: Create Database + + string connectionString = @"Data Source=(localdb)\" + InstanceName + $"; Integrated Security=True;"; + + if (!CheckDatabaseExists(connectionString, DatabaseName)) + { + //This is fixed -canot be changed + string UserPath = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); + + + SqlConnection connection = new SqlConnection(connectionString); + using (connection) + { + connection.Open(); + + string sql = $@" + CREATE DATABASE + {DatabaseName} + ON PRIMARY ( + NAME={DatabaseName}_data, + FILENAME = '{UserPath}\{DatabaseName}.mdf' + ) + LOG ON ( + NAME={DatabaseName}_log, + FILENAME = '{UserPath}\{DatabaseName}.ldf' + )"; + + SqlCommand command = new SqlCommand(sql, connection); + try + { + command.ExecuteNonQuery(); + } + catch (Exception ex) + { + MessageBox.Show($"CRITICAL ERROR: Database cannot be created\r\n{ex.ToString()}\r\nDoes Db exists in another instance?\r\n(Note: You cannot duplicate names across instances- requires unique name)"); + //You can debug using commandline + //>sqllocaldb info mssqllocaldb + + //https://docs.microsoft.com/en-us/sql/tools/sqllocaldb-utility?view=sql-server-ver15 + + string url = @"https://docs.microsoft.com/en-us/sql/relational-databases/express-localdb-instance-apis/command-line-management-tool-sqllocaldb-exe?view=sql-server-ver15"; + Process.Start(url); + + Application.Exit(); + } + + MessageBox.Show($" A New empty Local Database has been created successfully!\r\n\r\nSQLLOCALDB:{InstanceName}\r\nDATABASE:{DatabaseName}"); + } + } + } + + static bool CreateLocalDBInstance(string InstanceName) + { + // Lists all instances + // >sqllocaldb info + + // Start the child process. + Process p = new Process(); + // Redirect the output stream of the child process. + p.StartInfo.UseShellExecute = false; + p.StartInfo.RedirectStandardOutput = true; + p.StartInfo.FileName = "cmd.exe"; + p.StartInfo.Arguments = $"/C sqllocaldb c {InstanceName}"; //Create Local Db Instance + p.StartInfo.CreateNoWindow = true; + p.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; + p.Start(); + string sOutput = p.StandardOutput.ReadToEnd(); + p.WaitForExit(); + + //If LocalDb is not installed then it will return that 'sqllocaldb' is not recognized as an internal or external command operable program or batch file. + if (sOutput == null || sOutput.Trim().Length == 0 || sOutput.Contains("not recognized")) + return false; + if (sOutput.ToLower().Contains(InstanceName)) + return true; + return false; + } + + public static bool CheckDatabaseExists(string connectionString, string databaseName) + { + + using (var connection = new SqlConnection(connectionString)) + { + using (var command = new SqlCommand($"SELECT db_id('{databaseName}')", connection)) + { + connection.Open(); + var retval = command.ExecuteScalar(); + + return (retval != DBNull.Value); + } + } + } + } +} \ No newline at end of file diff --git a/src/Examples/EF6/Ex6_Course/Properties/AssemblyInfo.cs b/src/Examples/EF6/Ex6_Course/Properties/AssemblyInfo.cs new file mode 100644 index 000000000..d319e7ac0 --- /dev/null +++ b/src/Examples/EF6/Ex6_Course/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("Ex5_Course")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("Ex5_Course")] +[assembly: AssemblyCopyright("Copyright © 2021")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("bf56f02e-dceb-413d-8de6-a1ffa71870a8")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/src/Examples/EF6/Ex6_Course/Properties/Resources.Designer.cs b/src/Examples/EF6/Ex6_Course/Properties/Resources.Designer.cs new file mode 100644 index 000000000..e9ae9c633 --- /dev/null +++ b/src/Examples/EF6/Ex6_Course/Properties/Resources.Designer.cs @@ -0,0 +1,63 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace Ex5_Course.Properties { + using System; + + + /// + /// A strongly-typed resource class, for looking up localized strings, etc. + /// + // This class was auto-generated by the StronglyTypedResourceBuilder + // class via a tool like ResGen or Visual Studio. + // To add or remove a member, edit your .ResX file then rerun ResGen + // with the /str option, or rebuild your VS project. + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + internal class Resources { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal Resources() { + } + + /// + /// Returns the cached ResourceManager instance used by this class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Resources.ResourceManager ResourceManager { + get { + if (object.ReferenceEquals(resourceMan, null)) { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Ex5_Course.Properties.Resources", typeof(Resources).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// + /// Overrides the current thread's CurrentUICulture property for all + /// resource lookups using this strongly typed resource class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Globalization.CultureInfo Culture { + get { + return resourceCulture; + } + set { + resourceCulture = value; + } + } + } +} diff --git a/src/Examples/EF6/Ex6_Course/Properties/Resources.resx b/src/Examples/EF6/Ex6_Course/Properties/Resources.resx new file mode 100644 index 000000000..af7dbebba --- /dev/null +++ b/src/Examples/EF6/Ex6_Course/Properties/Resources.resx @@ -0,0 +1,117 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/src/Examples/EF6/Ex6_Course/Properties/Settings.Designer.cs b/src/Examples/EF6/Ex6_Course/Properties/Settings.Designer.cs new file mode 100644 index 000000000..a574cacf5 --- /dev/null +++ b/src/Examples/EF6/Ex6_Course/Properties/Settings.Designer.cs @@ -0,0 +1,26 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace Ex5_Course.Properties { + + + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "16.10.0.0")] + internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { + + private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); + + public static Settings Default { + get { + return defaultInstance; + } + } + } +} diff --git a/src/Examples/EF6/Ex6_Course/Properties/Settings.settings b/src/Examples/EF6/Ex6_Course/Properties/Settings.settings new file mode 100644 index 000000000..39645652a --- /dev/null +++ b/src/Examples/EF6/Ex6_Course/Properties/Settings.settings @@ -0,0 +1,7 @@ + + + + + + + diff --git a/src/Examples/EF6/README.md b/src/Examples/EF6/README.md new file mode 100644 index 000000000..02fe06702 --- /dev/null +++ b/src/Examples/EF6/README.md @@ -0,0 +1,37 @@ +# Entity Framework Visual Editor - Examples +An open source EF GUI tool works and here are some examples of how you get setup to use it.. +ENTITY FRAMEWORK is a modern ORM way of using DB access. EF itself is robust and solid + +## This tool makes it easy to visualise, create and maintain complex relational databases +Uses GUI models and classes to setup data that is then easily stored in a Database. + +## What about Microsofts ADO.Net Visual Modeller [.edmx] +The Entity framework Microsoft ADO.Net modeller GUI wrapper for 'Code first' and 'Fluent API' modelling tool .edmx is **fragile and incomplete.** + +### Microsofts GUI Database Model tool ".EDMX" visual tools DO NOT WORK +https://docs.microsoft.com/en-us/visualstudio/data-tools/entity-data-model-tools-in-visual-studio?view=vs-2019 + +Unfortunatley the 'Code first' and 'Fluent API' are console like commands that require a deep dive to utilise and apply to your requirements. +Not using a GUI tool means 10K hrs investment to become proficent :( + + +### Not using an ORM ? + The no ORM (Object Relationship Model) of doing Basic Database Operations is using C# hand crafted SQL CRUD [Create/Read/Update /Delete] + Works for simple database work but does not scale and is hard to maintiain / visualise. + https://www.geeksforgeeks.org/basic-database-operations-using-c-sharp/ + + +# EF Designer Examples +Examples using 'EF Designer' visual designer surface for Entity Framework code-first code generation for EF6, Core and beyond + +- E1_ModelPerson + +- Ex2_ModelOne2One + +- Ex3_ModelManytoMany + +- Ex4_ModelInvoice + +- Ex5_Store + +- Ex6_Course