Base solution for your next web application
Ends in:
01 DAYS
01 HRS
01 MIN
01 SEC
Open Closed

How to build application using the already existing database #4891


User avatar
0
manojreddy created

I have an existing database on SQL server, But I don't have the model classes or the backend C# code(only the database which has tables, SPs, and triggers). I want to build a Web application on top of this already existing database using aspnetzero framework, means I want to use the already existing database also and start my web application using this database. I want to use the existing database tables, SPs, and triggers also.

Is there any way to generate the migration, dbcontext, and snapshot of this already existing database, so that If need to add/modify the existing tables/SPs/Triggers, I can create using the code first approach.

So could you please let me know what could be the best approach to proceed with this kind of requirement?


13 Answer(s)
  • User Avatar
    0
    ismcagdas created
    Support Team

    Hi @ManojReddy,

    You can use reverse POCO generator (<a class="postlink" href="https://marketplace.visualstudio.com/items?itemName=SimonHughes.EntityFrameworkReversePOCOGenerator">https://marketplace.visualstudio.com/it ... OGenerator</a>) or something similar to generate entity classes.

    Then, add a migration and remove your tables from this migration since you already have tables created. If you have similar tables in ABP Framework like User, Role tables, you need to use ABP's tables to authenticate users.

  • User Avatar
    0
    manojreddy created

    It doesn't have support for EF Core.

    Any other suggestions?

  • User Avatar
    0
    ismcagdas created
    Support Team

    @ManojReddy same approach can work with EF 6.x I guess. Have you tried ? If so, did you have a problem ?

  • User Avatar
    0
    JeffMH created

    I am actually going through this same process right now and it's a bit cumbersome. Just for reference if anyone wants to know, we are using this to generate entities (we only generate them once):

    <a class="postlink" href="https://github.com/ErikEJ/SqlCeToolbox/wiki/EF-Core-Power-Tools">https://github.com/ErikEJ/SqlCeToolbox/ ... ower-Tools</a>

    We generate them once because we have to change them to be ABP entities (Base Classes, Interfaces, etc). It's possible but difficult to update the output of that process so we generate them up front, then all changes going forward are done code first.

    But, back to my struggle. I am really debating on going back to EF 6 simply to be able to use some T4 templates to generate code. Going from an existing database with varying degrees of standards across the tables (primary keys, audit columns) is difficult when coming from an existing database. So, we are creating several workarounds to get it to play nicely with ABP. Plus, ABP system is merely one system in several so there are some database objects that really shouldn't be a part of this code base. I know, that's not ideal, but this is a large client, with many years of technology in production.

    So, my question is can we take the current version of the downloaded Angular project that uses the full framework and switch out to use the EF6 libraries and not the Core libraries. I would have to code the seeds differently and a few things but I have all that code in other projects so I am just wondering if the EF 6 and EF Core projects are somewhat interchangeable???

    Thoughts?

  • User Avatar
    0
    bbakermmc created

    Just make a .net 4.7 project to generate your code with T4s, then move the files manually.

  • User Avatar
    0
    JeffMH created

    I thought about that as well but it seems a little hackish. Although I can't say other things I am doing don't feel the same way.

    So we have to generate a couple things right, first the entities and then the context. The context needs to be generated with .net core code because the fluent API is different in core. The Entities could be generated in EF 6. I don't know, maybe I will try that tomorrow. I am already using a T4 template (ReversePocoGenerator) for EF6 in another project so I could generate entities with it, and generate the first round of Context code with the one I am using above.

    Ugh, sounds fugly just saying it out loud lol.

    Do you do this currently? I would be curious to know what process you follow.

  • User Avatar
    0
    bbakermmc created

    I posted an example here: <a class="postlink" href="https://github.com/aspnetzero/aspnet-zero-core/issues/1056">https://github.com/aspnetzero/aspnet-ze ... ssues/1056</a>

    Why do you need to use fluent design? There something specific you need that cant be done via the models? I use this mainly for the models. I modified the source code a little for our use cases, but Im looking at building out some T4 to do the same thing. Also the T4 could generate .net core code, since at that point its just generating text. <a class="postlink" href="https://www.codeproject.com/Articles/892233/POCO-Generator">https://www.codeproject.com/Articles/89 ... -Generator</a>

    I was never a fan of the RadTools. We have DBAs that generate our tables and use DevExtreme controls, seems like they spending a bunch of time on RadTools though instead of just writing some basic T4s. Very basic things like just adding a new permission or navigation node are missing from the tool set unless you make a new entry. Why?!?!

    T4s seems to be the "easiest" way for now. I dont see a problem with making a new project thats not .net core based, we will only use it to generate the templates and move the code into the existing project locations.

  • User Avatar
    0
    JeffMH created

    So, through the day to day you are right, we are not using fluent API for much of anything, but in the beginning, the generator kicks out some items in the OnModelCreating event that adds all the indexes and other model stuff that isn't easily represented in attributes. I could for the most part generate the entities in T4, then true up anything that is left in the OnModelCreating. Does that make sense? Just talking about the code that is generated within the context class.

    I'll give the entities a try today and see how it goes. I very much appreciate the input and links. I will check back in once I am done.

    Thanks

  • User Avatar
    0
    bbakermmc created

    Again not sure what the fluent gives you :p

    Example:

    // <auto-generated>
    // ReSharper disable ConvertPropertyToExpressionBody
    // ReSharper disable DoNotCallOverridableMethodsInConstructor
    // ReSharper disable EmptyNamespace
    // ReSharper disable InconsistentNaming
    // ReSharper disable PartialMethodWithSinglePart
    // ReSharper disable PartialTypeWithSinglePart
    // ReSharper disable RedundantNameQualifier
    // ReSharper disable RedundantOverridenMember
    // ReSharper disable UseNameofExpression
    // TargetFrameworkVersion = 4.7
    #pragma warning disable 1591    //  Ignore "Missing XML Comment" warning
    
    using System.ComponentModel.DataAnnotations;
    using System.ComponentModel.DataAnnotations.Schema;
    
    namespace MMC.Templates.Models
    {
        using Newtonsoft.Json;
    
        // BRC
        ///<summary>
        /// A BRC that was part of a package.
        ///</summary>
        [Table("BRC", Schema = "dbo")]
        [System.CodeDom.Compiler.GeneratedCode("EF.Reverse.POCO.Generator", "2.36.1.0")]
        public partial class BRC : AuditBase<int>
        {
    
            ///<summary>
            /// BRCId (Primary key). Unique identifier of the BRC.
            ///</summary>
            [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
            [Column(@"BRCId", Order = 1, TypeName = "int")]
            [Index(@"PK_BRC", 1, IsUnique = true, IsClustered = true)]
            [Required]
            [Key]
            [Display(Name = "Brci d")]
            public override int Id { get; set; }
    
            ///<summary>
            /// PackageId. Identifier of the package that was delivered during the interaction.
            ///</summary>
            [Column(@"PackageId", Order = 2, TypeName = "int")]
            [Index(@"FK_BRC_PackageId", 1, IsUnique = false, IsClustered = false)]
            [Index(@"AK_BRC_PackageId", 1, IsUnique = true, IsClustered = false)]
            [Required]
            [Display(Name = "Package ID")]
            public int PackageId { get; set; }
    
            ///<summary>
            /// BRCTypeId. Link to BRCType table.
            ///</summary>
            [Column(@"BRCTypeId", Order = 3, TypeName = "smallint")]
            [Index(@"FK_BRC_BRCTypeId", 1, IsUnique = false, IsClustered = false)]
            [Required]
            [Display(Name = "Brct ype ID")]
            public short BRCTypeId { get; set; }
    
            ///<summary>
            /// Instructions. Instructions provided to the user about how to process the BRC.
            ///</summary>
            [Column(@"Instructions", Order = 4, TypeName = "varchar(max)")]
            [Display(Name = "Instructions")]
            public string Instructions { get; set; }
    
            ///<summary>
            /// ImagePath (length: 255). reference to the image of the BRC.
            ///</summary>
            [Column(@"ImagePath", Order = 5, TypeName = "varchar")]
            [MaxLength(255)]
            [StringLength(255)]
            [Display(Name = "Image path")]
            public string ImagePath { get; set; }
    
            ///<summary>
            /// isActive. Indicates if the BRC is still Active.
            /// 0 = Is not Active
            /// 1 = Active
            ///</summary>
            [Column(@"isActive", Order = 6, TypeName = "bit")]
            [Required]
            [Display(Name = "Is active")]
            public bool isActive { get; set; } = true;
    
            ///<summary>
            /// Inserted. The date/time that the row was inserted.
            ///</summary>
            [Column(@"Inserted", Order = 7, TypeName = "datetime")]
            [Required]
            [Display(Name = "Inserted")]
            public System.DateTime Inserted { get; set; } = System.DateTime.Now;
    
            ///<summary>
            /// Updated. The date/time that the row was last updated.
            ///</summary>
            [Column(@"Updated", Order = 8, TypeName = "datetime")]
            [Required]
            [Display(Name = "Updated")]
            public System.DateTime Updated { get; set; } = System.DateTime.Now;
    
            ///<summary>
            /// InsertedBy (length: 128). The user or process that inserted the row.
            ///</summary>
            [Column(@"InsertedBy", Order = 9, TypeName = "varchar")]
            [Required]
            [MaxLength(128)]
            [StringLength(128)]
            [Display(Name = "Inserted by")]
            public string InsertedBy { get; set; } = "left(rtrim((host_name()+'-')+suser_sname()),(128))";
    
            ///<summary>
            /// UpdatedBy (length: 128). The user or process that last updated the row.
            ///</summary>
            [Column(@"UpdatedBy", Order = 10, TypeName = "varchar")]
            [Required]
            [MaxLength(128)]
            [StringLength(128)]
            [Display(Name = "Updated by")]
            public string UpdatedBy { get; set; } = "left(rtrim((host_name()+'-')+suser_sname()),(128))";
    
            ///<summary>
            /// EditCount. The number of times the row has been updated. Used for concurrent update checks.
            ///</summary>
            [Column(@"EditCount", Order = 11, TypeName = "int")]
            [Required]
            [Display(Name = "Edit count")]
            public int EditCount { get; set; } = 1;
    
            // Foreign keys
    
            /// <summary>
            /// Parent BRCType pointed by [BRC].([BRCTypeId]) (R_BRC_BRCTypeId)
            /// </summary>
            [ForeignKey("BRCTypeId"), Required] public BRCType BRCType { get; set; } // R_BRC_BRCTypeId
    
            /// <summary>
            /// Parent Package pointed by [BRC].([PackageId]) (R_BRC_PackageId)
            /// </summary>
            [ForeignKey("PackageId"), Required] public Package Package { get; set; } // R_BRC_PackageId
        }
    
    }
    // </auto-generated>
    

    vs

    public BRCConfiguration(string schema)
            {
                ToTable("BRC", schema);
                HasKey(x => x.Id);
    
                Property(x => x.Id).HasColumnName(@"BRCId").HasColumnType("int").IsRequired().HasDatabaseGeneratedOption(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.Identity);
                Property(x => x.PackageId).HasColumnName(@"PackageId").HasColumnType("int").IsRequired();
                Property(x => x.BRCTypeId).HasColumnName(@"BRCTypeId").HasColumnType("smallint").IsRequired();
                Property(x => x.Instructions).HasColumnName(@"Instructions").HasColumnType("varchar(max)").IsOptional().IsUnicode(false);
                Property(x => x.ImagePath).HasColumnName(@"ImagePath").HasColumnType("varchar").IsOptional().IsUnicode(false).HasMaxLength(255);
                Property(x => x.isActive).HasColumnName(@"isActive").HasColumnType("bit").IsRequired();
                Property(x => x.Inserted).HasColumnName(@"Inserted").HasColumnType("datetime").IsRequired();
                Property(x => x.Updated).HasColumnName(@"Updated").HasColumnType("datetime").IsRequired();
                Property(x => x.InsertedBy).HasColumnName(@"InsertedBy").HasColumnType("varchar").IsRequired().IsUnicode(false).HasMaxLength(128);
                Property(x => x.UpdatedBy).HasColumnName(@"UpdatedBy").HasColumnType("varchar").IsRequired().IsUnicode(false).HasMaxLength(128);
                Property(x => x.EditCount).HasColumnName(@"EditCount").HasColumnType("int").IsRequired();
    
                // Foreign keys
                HasRequired(a => a.BRCType).WithMany().HasForeignKey(c => c.BRCTypeId).WillCascadeOnDelete(false); // R_BRC_BRCTypeId
                HasRequired(a => a.Package).WithMany().HasForeignKey(c => c.PackageId).WillCascadeOnDelete(false); // R_BRC_PackageId
                InitializePartial();
            }
    // <auto-generated>
    // ReSharper disable ConvertPropertyToExpressionBody
    // ReSharper disable DoNotCallOverridableMethodsInConstructor
    // ReSharper disable EmptyNamespace
    // ReSharper disable InconsistentNaming
    // ReSharper disable PartialMethodWithSinglePart
    // ReSharper disable PartialTypeWithSinglePart
    // ReSharper disable RedundantNameQualifier
    // ReSharper disable RedundantOverridenMember
    // ReSharper disable UseNameofExpression
    // TargetFrameworkVersion = 4.7
    #pragma warning disable 1591    //  Ignore "Missing XML Comment" warning
    
    
    namespace MMC.Templates.Models
    {
        using Newtonsoft.Json;
    
        // BRC
        ///<summary>
        /// A BRC that was part of a package.
        ///</summary>
        [System.CodeDom.Compiler.GeneratedCode("EF.Reverse.POCO.Generator", "2.36.1.0")]
        public partial class BRC : AuditBase<int>
        {
    
            ///<summary>
            /// BRCId (Primary key). Unique identifier of the BRC.
            ///</summary>
            public override int Id { get; set; }
    
            ///<summary>
            /// PackageId. Identifier of the package that was delivered during the interaction.
            ///</summary>
            public int PackageId { get; set; }
    
            ///<summary>
            /// BRCTypeId. Link to BRCType table.
            ///</summary>
            public short BRCTypeId { get; set; }
    
            ///<summary>
            /// Instructions. Instructions provided to the user about how to process the BRC.
            ///</summary>
            public string Instructions { get; set; }
    
            ///<summary>
            /// ImagePath (length: 255). reference to the image of the BRC.
            ///</summary>
            public string ImagePath { get; set; }
    
            ///<summary>
            /// isActive. Indicates if the BRC is still Active.
            /// 0 = Is not Active
            /// 1 = Active
            ///</summary>
            public bool isActive { get; set; } = true;
    
            ///<summary>
            /// Inserted. The date/time that the row was inserted.
            ///</summary>
            public System.DateTime Inserted { get; set; } = System.DateTime.Now;
    
            ///<summary>
            /// Updated. The date/time that the row was last updated.
            ///</summary>
            public System.DateTime Updated { get; set; } = System.DateTime.Now;
    
            ///<summary>
            /// InsertedBy (length: 128). The user or process that inserted the row.
            ///</summary>
            public string InsertedBy { get; set; } = "left(rtrim((host_name()+'-')+suser_sname()),(128))";
    
            ///<summary>
            /// UpdatedBy (length: 128). The user or process that last updated the row.
            ///</summary>
            public string UpdatedBy { get; set; } = "left(rtrim((host_name()+'-')+suser_sname()),(128))";
    
            ///<summary>
            /// EditCount. The number of times the row has been updated. Used for concurrent update checks.
            ///</summary>
            public int EditCount { get; set; } = 1;
    
            // Foreign keys
    
            /// <summary>
            /// Parent BRCType pointed by [BRC].([BRCTypeId]) (R_BRC_BRCTypeId)
            /// </summary>
            public BRCType BRCType { get; set; } // R_BRC_BRCTypeId
    
            /// <summary>
            /// Parent Package pointed by [BRC].([PackageId]) (R_BRC_PackageId)
            /// </summary>
            public Package Package { get; set; } // R_BRC_PackageId
        }
    
    }
    // </auto-generated>
    
  • User Avatar
    0
    bbakermmc created

    Heres the TT. It has some customization's specific for us.

    <#@ include file="EF.Reverse.POCO.Core.ttinclude" #>
    <#
        // v2.36.1
        // Please make changes to the settings below.
        // All you have to do is save this file, and the output file(s) is/are generated. Compiling does not regenerate the file(s).
        // A course for this generator is available on Pluralsight at https://www.pluralsight.com/courses/code-first-entity-framework-legacy-databases
    
        // Main settings **********************************************************************************************************************
        Settings.ConnectionStringName = "DMP";   // Searches for this connection string in config files listed below in the ConfigFilenameSearchOrder setting
        // ConnectionStringName is the only required setting.
        Settings.CommandTimeout = 600; // SQL Command timeout in seconds. 600 is 10 minutes, 0 will wait indefinately. Some databases can be slow retrieving schema information.
        // As an alternative to ConnectionStringName above, which must match your app/web.config connection string name, you can override them below
        // Settings.ConnectionString = "Data Source=(local);Initial Catalog=Northwind;Integrated Security=True;Application Name=EntityFramework Reverse POCO Generator";
        // Settings.ProviderName = "System.Data.SqlClient";
    
        Settings.Namespace = DefaultNamespace; // Override the default namespace here
        Settings.DbContextName = "MyDbContext"; // Note: If generating separate files, please give the db context a different name from this tt filename.
        //Settings.DbContextInterfaceName = "IMyDbContext"; // Defaults to "I" + DbContextName or set string empty to not implement any interface.
        Settings.DbContextInterfaceBaseClasses = "System.IDisposable";    // Specify what the base classes are for your database context interface
        Settings.DbContextBaseClass = "System.Data.Entity.DbContext";   // Specify what the base class is for your DbContext. For ASP.NET Identity use "IdentityDbContext<ApplicationUser>"
        //Settings.DefaultConstructorArgument = "EnvironmentConnectionStrings.MyDbContext"; //defaults to "Name=" + ConnectionStringName
        Settings.ConfigurationClassName = "Configuration"; // Configuration, Mapping, Map, etc. This is appended to the Poco class name to configure the mappings.
        Settings.FilenameSearchOrder = new[] { "app.config", "web.config" }; // Add more here if required. The config files are searched for in the local project first, then the whole solution second.
        Settings.GenerateSeparateFiles = true;
        Settings.MakeClassesInternal = false;
        Settings.MakeClassesPartial = true;
        Settings.MakeDbContextInterfacePartial = false;
        Settings.UseMappingTables = true; // If true, mapping will be used and no mapping tables will be generated. If false, all tables will be generated.
        Settings.UsePascalCase = false;    // This will rename the generated C# tables & properties to use PascalCase. If false table & property names will be left alone.
        Settings.UseDataAnnotations = true; // If true, will add data annotations to the poco classes.
        Settings.UsePropertyInitializers = true; // Removes POCO constructor and instead uses C# 6 property initialisers to set defaults
        Settings.UseLazyLoading = false; // Marks all navigation properties as virtual or not, to support or disable EF Lazy Loading feature
        Settings.IncludeComments = CommentsStyle.InSummaryBlock; // Adds comments to the generated code
        Settings.IncludeExtendedPropertyComments = CommentsStyle.InSummaryBlock; // Adds extended properties as comments to the generated code
        Settings.IncludeConnectionSettingComments = false; // Add comments describing connection settings used to generate file
        Settings.IncludeViews = false;
        Settings.IncludeSynonyms = false;
        Settings.IncludeStoredProcedures = false;
        Settings.IncludeTableValuedFunctions = false; // If true, you must set IncludeStoredProcedures = true, and install the "EntityFramework.CodeFirstStoreFunctions" Nuget Package.
        Settings.DisableGeographyTypes = false; // Turns off use of System.Data.Entity.Spatial.DbGeography and System.Data.Entity.Spatial.DbGeometry as OData doesn't support entities with geometry/geography types.
        //Settings.CollectionInterfaceType = "System.Collections.Generic.List"; // Determines the declaration type of collections for the Navigation Properties. ICollection is used if not set.
        Settings.CollectionType = "System.Collections.Generic.List";  // Determines the type of collection for the Navigation Properties. "ObservableCollection" for example. Add "System.Collections.ObjectModel" to AdditionalNamespaces if setting the CollectionType = "ObservableCollection".
        Settings.NullableShortHand = true; //true => T?, false => Nullable<T>
        Settings.AddIDbContextFactory = false; // Will add a default IDbContextFactory<DbContextName> implementation for easy dependency injection
        Settings.AddUnitTestingDbContext = false; // Will add a FakeDbContext and FakeDbSet for easy unit testing
        Settings.IncludeQueryTraceOn9481Flag = false; // If SqlServer 2014 appears frozen / take a long time when this file is saved, try setting this to true (you will also need elevated privileges).
        Settings.IncludeCodeGeneratedAttribute = true; // If true, will include the GeneratedCode attribute, false to remove it.
        Settings.UsePrivateSetterForComputedColumns = true; // If the columns is computed, use a private setter.
        Settings.AdditionalNamespaces = new[] { "Newtonsoft.Json" };  // To include extra namespaces, include them here. i.e. "Microsoft.AspNet.Identity.EntityFramework"
        Settings.AdditionalContextInterfaceItems = new[] // To include extra db context interface items, include them here. Also set MakeClassesPartial=true, and implement the partial DbContext class functions.
        {
            ""  //  example: "void SetAutoDetectChangesEnabled(bool flag);"
        };
        // If you need to serialize your entities with the JsonSerializer from Newtonsoft, this would serialize
        // all properties including the Reverse Navigation and Foreign Keys. The simplest way to exclude them is
        // to use the data annotation [JsonIgnore] on reverse navigation and foreign keys.
        // For more control, take a look at ForeignKeyAnnotationsProcessing() further down
        Settings.AdditionalReverseNavigationsDataAnnotations = new string[] // Data Annotations for all ReverseNavigationProperty.
        {
             "JsonIgnore" // Also add "Newtonsoft.Json" to the AdditionalNamespaces array above
        };
        Settings.AdditionalForeignKeysDataAnnotations = new string[] // Data Annotations for all ForeignKeys.
        {
            // "JsonIgnore" // Also add "Newtonsoft.Json" to the AdditionalNamespaces array above
        };
        Settings.ColumnNameToDataAnnotation = new Dictionary<string, string>
        {
            // This is used when UseDataAnnotations = true;
            // It is used to set a data annotation on a column based on the columns name.
            // Make sure the column name is lowercase in the following array, regardless of how it is in the database
            // Column name       DataAnnotation to add
            { "email",           "EmailAddress" },
            { "emailaddress",    "EmailAddress" },
            { "creditcard",      "CreditCard" },
            { "url",             "Url" },
            { "phone",           "Phone" },
            { "phonenumber",     "Phone" },
            { "mobile",          "Phone" },
            { "mobilenumber",    "Phone" },
            { "telephone",       "Phone" },
            { "telephonenumber", "Phone" },
            { "password",        "DataType(DataType.Password)" },
            { "username",        "DataType(DataType.Text)" }
        };
    
        // Migrations *************************************************************************************************************************
        Settings.MigrationConfigurationFileName = ""; // null or empty to not create migrations
        Settings.MigrationStrategy = "MigrateDatabaseToLatestVersion"; // MigrateDatabaseToLatestVersion, CreateDatabaseIfNotExists or DropCreateDatabaseIfModelChanges
        Settings.ContextKey = ""; // Sets the string used to distinguish migrations belonging to this configuration from migrations belonging to other configurations using the same database. This property enables migrations from multiple different models to be applied to applied to a single database.
        Settings.AutomaticMigrationsEnabled = false;
        Settings.AutomaticMigrationDataLossAllowed = false; // if true, can drop fields and lose data during automatic migration
    
        // Pluralization **********************************************************************************************************************
        // To turn off pluralization, use:
        //      Inflector.PluralizationService = null;
        // Default pluralization, use:
        //      Inflector.PluralizationService = new EnglishPluralizationService();
        // For Spanish pluralization:
        //      1. Intall the "EF6.Contrib" Nuget Package.
        //      2. Add the following to the top of this file and adjust path, and remove the space between the angle bracket and # at the beginning and end.
        //         < #@ assembly name="your full path to \EntityFramework.Contrib.dll" # >
        //      3. Change the line below to: Inflector.PluralizationService = new SpanishPluralizationService();
        Inflector.PluralizationService = null;
        // If pluralisation does not do the right thing, override it here by adding in a custom entry.
        //Inflector.PluralizationService = new EnglishPluralizationService(new[]
        //{
        //    // Create custom ("Singular", "Plural") forms for one-off words as needed.
        //    new CustomPluralizationEntry("Course", "Courses"),
        //    new CustomPluralizationEntry("Status", "Status") // Use same value to prevent pluralisation
        //});
    
    
        // Elements to generate ***************************************************************************************************************
        // Add the elements that should be generated when the template is executed.
        // Multiple projects can now be used that separate the different concerns.
        Settings.ElementsToGenerate = Elements.Poco | Elements.Context;// | Elements.PocoConfiguration;//| Elements.UnitOfWork | Elements.PocoConfiguration;
    
        // Use these namespaces to specify where the different elements now live. These may even be in different assemblies.
        // Please note this does not create the files in these locations, it only adds a using statement to say where they are.
        // The way to do this is to add the "EntityFramework Reverse POCO Code First Generator" into each of these folders.
        // Then set the .tt to only generate the relevant section you need by setting
        //      ElementsToGenerate = Elements.Poco; in your Entity folder,
        //      ElementsToGenerate = Elements.Context | Elements.UnitOfWork; in your Context folder,
        //      ElementsToGenerate = Elements.PocoConfiguration; in your Maps folder.
        //      PocoNamespace = "YourProject.Entities";
        //      ContextNamespace = "YourProject.Context";
        //      UnitOfWorkNamespace = "YourProject.Context";
        //      PocoConfigurationNamespace = "YourProject.Maps";
        // You also need to set the following to the namespace where they now live:
        Settings.PocoNamespace = "";
        Settings.ContextNamespace = "";
        Settings.UnitOfWorkNamespace = "";
        Settings.PocoConfigurationNamespace = "";
    
    
        // Schema *****************************************************************************************************************************
        // If there are multiple schemas, then the table name is prefixed with the schema, except for dbo.
        // Ie. dbo.hello will be Hello.
        //     abc.hello will be AbcHello.
        Settings.PrependSchemaName = true;   // Control if the schema name is prepended to the table name
    
        // Table Suffix ***********************************************************************************************************************
        // Prepends the suffix to the generated classes names
        // Ie. If TableSuffix is "Dto" then Order will be OrderDto
        //     If TableSuffix is "Entity" then Order will be OrderEntity
        Settings.TableSuffix = null;
    
        // Filtering **************************************************************************************************************************
        // Use the following table/view name regex filters to include or exclude tables/views
        // Exclude filters are checked first and tables matching filters are removed.
        //  * If left null, none are excluded.
        //  * If not null, any tables matching the regex are excluded.
        // Include filters are checked second.
        //  * If left null, all are included.
        //  * If not null, only the tables matching the regex are included.
        // For clarity: if you want to include all the customer tables, but not the customer billing tables.
        //      TableFilterInclude = new Regex("^[Cc]ustomer.*"); // This includes all the customer and customer billing tables
        //      TableFilterExclude = new Regex(".*[Bb]illing.*"); // This excludes all the billing tables
        //
        // Example:     TableFilterExclude = new Regex(".*auto.*");
        //              TableFilterInclude = new Regex("(.*_FR_.*)|(data_.*)");
        //              TableFilterInclude = new Regex("^table_name1$|^table_name2$|etc");
        //              ColumnFilterExclude = new Regex("^FK_.*$");
        Settings.SchemaFilterExclude = null;
        Settings.SchemaFilterInclude = null;
        Settings.TableFilterExclude = null;
        Settings.TableFilterInclude = null;
        Settings.ColumnFilterExclude = null;
    
        // Filtering of tables using a function. This can be used in conjunction with the Regex's above.
        // Regex are used first to filter the list down, then this function is run last.
        // Return true to include the table, return false to exclude it.
        Settings.TableFilter = (Table t) =>
        {
            // Example: Exclude any table in dbo schema with "order" in its name.
            //if(t.Schema.Equals("dbo", StringComparison.InvariantCultureIgnoreCase) && t.NameHumanCase.ToLowerInvariant().Contains("order"))
            //    return false;
    
            return true;
        };
    
    
        // Stored Procedures ******************************************************************************************************************
        // Use the following regex filters to include or exclude stored procedures
        Settings.StoredProcedureFilterExclude = null;
        Settings.StoredProcedureFilterInclude = null;
    
        // Filtering of stored procedures using a function. This can be used in conjunction with the Regex's above.
        // Regex are used first to filter the list down, then this function is run last.
        // Return true to include the stored procedure, return false to exclude it.
        Settings.StoredProcedureFilter = (StoredProcedure sp) =>
        {
            // Example: Exclude any stored procedure in dbo schema with "order" in its name.
            //if(sp.Schema.Equals("dbo", StringComparison.InvariantCultureIgnoreCase) && sp.NameHumanCase.ToLowerInvariant().Contains("order"))
            //    return false;
    
            return true;
        };
    
    
        // Table renaming *********************************************************************************************************************
        // Use the following function to rename tables such as tblOrders to Orders, Shipments_AB to Shipments, etc.
        // Example:
        Settings.TableRename = (string name, string schema, bool isView) =>
        {
            // Example
            //if (name.StartsWith("tbl"))
            //    name = name.Remove(0, 3);
            //name = name.Replace("_AB", "");
    
            //if(isView)
            //    name = name + "View";
    
            // If you turn pascal casing off (UsePascalCase = false), and use the pluralisation service, and some of your
            // tables names are all UPPERCASE, some words ending in IES such as CATEGORIES get singularised as CATEGORy.
            // Therefore you can make them lowercase by using the following
            // return Inflector.MakeLowerIfAllCaps(name);
    
            // If you are using the pluralisation service and you want to rename a table, make sure you rename the table to the plural form.
            // For example, if the table is called Treez (with a z), and your pluralisation entry is
            //     new CustomPluralizationEntry("Tree", "Trees")
            // Use this TableRename function to rename Treez to the plural (not singular) form, Trees:
            // if (name == "Treez") return "Trees";
    
            return name;
        };
    
        // Column modification*****************************************************************************************************************
        // Use the following list to replace column byte types with Enums.
        // As long as the type can be mapped to your new type, all is well.
        //Settings.EnumDefinitions.Add(new EnumDefinition { Schema = "dbo", Table = "match_table_name", Column = "match_column_name", EnumType = "name_of_enum" });
        //Settings.EnumDefinitions.Add(new EnumDefinition { Schema = "dbo", Table = "OrderHeader", Column = "OrderStatus", EnumType = "OrderStatusType" }); // This will replace OrderHeader.OrderStatus type to be an OrderStatusType enum
    
        // Use the following function if you need to apply additional modifications to a column
        // eg. normalise names etc.
        Settings.UpdateColumn = (Column column, Table table) =>
        {
            // Rename column
            //if (column.IsPrimaryKey && column.NameHumanCase == "PkId")
            //    column.NameHumanCase = "Id";
    
            // .IsConcurrencyToken() must be manually configured. However .IsRowVersion() can be automatically detected.
            //if (table.NameHumanCase.Equals("SomeTable", StringComparison.InvariantCultureIgnoreCase) && column.NameHumanCase.Equals("SomeColumn", StringComparison.InvariantCultureIgnoreCase))
            //    column.IsConcurrencyToken = true;
    
            // Remove table name from primary key
    	    if (column.IsPrimaryKey && column.NameHumanCase.Equals(table.NameHumanCase + "Id", StringComparison.InvariantCultureIgnoreCase))
    	    {
    		    column.NameHumanCase    = "Id";
    		    column.OverrideModifier = true;
    	    }
    
    	    // Remove column from poco class as it will be inherited from a base class
            //if (column.IsPrimaryKey && table.NameHumanCase.Equals("SomeTable", StringComparison.InvariantCultureIgnoreCase))
            //    column.Hidden = true;
    
            // Use the extended properties to perform tasks to column
            //if (column.ExtendedProperty == "HIDE")
            //    column.Hidden = true;
    
            // Apply the "override" access modifier to a specific column.
            // if (column.NameHumanCase == "id")
            //    column.OverrideModifier = true;
            // This will create: public override long id { get; set; }
    
            // Perform Enum property type replacement
            var enumDefinition = Settings.EnumDefinitions.FirstOrDefault(e =>
                (e.Schema.Equals(table.Schema, StringComparison.InvariantCultureIgnoreCase)) &&
                (e.Table.Equals(table.Name, StringComparison.InvariantCultureIgnoreCase) || e.Table.Equals(table.NameHumanCase, StringComparison.InvariantCultureIgnoreCase)) &&
                (e.Column.Equals(column.Name, StringComparison.InvariantCultureIgnoreCase) || e.Column.Equals(column.NameHumanCase, StringComparison.InvariantCultureIgnoreCase)));
    
            if (enumDefinition != null)
            {
                column.PropertyType = enumDefinition.EnumType;
                if(!string.IsNullOrEmpty(column.Default))
                    column.Default = "(" + enumDefinition.EnumType + ") " + column.Default;
            }
    
            return column;
        };
    
        // StoredProcedure renaming ************************************************************************************************************
        // Use the following function to rename stored procs such as sp_CreateOrderHistory to CreateOrderHistory, my_sp_shipments to Shipments, etc.
        // Example:
        /*Settings.StoredProcedureRename = (sp) =>
        {
            if (sp.NameHumanCase.StartsWith("sp_"))
                return sp.NameHumanCase.Remove(0, 3);
            return sp.NameHumanCase.Replace("my_sp_", "");
        };*/
        Settings.StoredProcedureRename = (sp) => sp.NameHumanCase;   // Do nothing by default
    
        // Use the following function to rename the return model automatically generated for stored procedure.
        // By default it's <proc_name>ReturnModel.
        // Example:
        /*Settings.StoredProcedureReturnModelRename = (name, sp) =>
        {
            if (sp.NameHumanCase.Equals("ComputeValuesForDate", StringComparison.InvariantCultureIgnoreCase))
                return "ValueSet";
            if (sp.NameHumanCase.Equals("SalesByYear", StringComparison.InvariantCultureIgnoreCase))
                return "SalesSet";
    
            return name;
        };*/
        Settings.StoredProcedureReturnModelRename = (name, sp) => name; // Do nothing by default
    
        // StoredProcedure return types *******************************************************************************************************
        // Override generation of return models for stored procedures that return entities.
        // If a stored procedure returns an entity, add it to the list below.
        // This will suppress the generation of the return model, and instead return the entity.
        // Example:                       Proc name      Return this entity type instead
        //StoredProcedureReturnTypes.Add("SalesByYear", "SummaryOfSalesByYear");
    
    
        // Callbacks **********************************************************************************************************************
        // This method will be called right before we write the POCO header.
        Action<Table> WritePocoClassAttributes = t =>
        {
            if (Settings.UseDataAnnotations)
            {
                foreach (var dataAnnotation in t.DataAnnotations)
                {
                    WriteLine("    [" + dataAnnotation + "]");
                }
            }
    
            // Example:
            // if(t.ClassName.StartsWith("Order"))
            //     WriteLine("    [SomeAttribute]");
        };
    
        // This method will be called right before we write the POCO header.
        Action<Table> WritePocoClassExtendedComments = t =>
        {
            if (Settings.IncludeExtendedPropertyComments != CommentsStyle.None && !string.IsNullOrEmpty(t.ExtendedProperty))
            {
                var lines = t.ExtendedProperty
                    .Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries)
                    .ToList();
                WriteLine("    ///<summary>");
    			foreach(var line in lines)
    			{
    				WriteLine("    /// {0}", System.Security.SecurityElement.Escape(line));
    			}
                WriteLine("    ///</summary>");
            }
        };
    
        // Writes optional base classes
        Func<Table, string> WritePocoBaseClasses = t =>
        {
            //if (t.ClassName == "User")
            //    return ": IdentityUser<int, CustomUserLogin, CustomUserRole, CustomUserClaim>";
    
            // Or use the maker class to dynamically build more complex definitions
            /* Example:
            var r = new BaseClassMaker("POCO.Sample.Data.MetaModelObject");
            r.AddInterface("POCO.Sample.Data.IObjectWithTableName");
            r.AddInterface("POCO.Sample.Data.IObjectWithId",
                t.Columns.Any(x => x.IsPrimaryKey && !x.IsNullable && x.NameHumanCase.Equals("Id", StringComparison.InvariantCultureIgnoreCase) && x.PropertyType == "long"));
            r.AddInterface("POCO.Sample.Data.IObjectWithUserId",
                t.Columns.Any(x => !x.IsPrimaryKey && !x.IsNullable && x.NameHumanCase.Equals("UserId", StringComparison.InvariantCultureIgnoreCase) && x.PropertyType == "long"));
            return r.ToString();
            */
    
    	    var hasInserted = false;
    	    var hasUpdated = false;
    	    var hasEditCount = false;
    	    var hasInsertedBy = false;
    	    var hasUpdatedBy = false;
    	    var hasDisplayText = false;
    	    var hasDisplayFlag = false;
    	    var hasDisplaySequence = false;
    	    var hasDescription = false;
    		
    	    var isAuditBase = false;
    	    var isCodeTableBase = false;
    
    	    var pkType = string.Empty;
    
    	    foreach (Column column in t.Columns)
    	    {
    		    switch (column.Name)
    		    {
    			    case "Inserted":
    				    hasInserted = true;
    				    break;
    			    case "Updated":
    				    hasUpdated = true;
    				    break;
    			    case "InsertedBy":
    				    hasInsertedBy = true;
    				    break;
    			    case "UpdatedBy":
    				    hasUpdatedBy = true;
    				    break;
    			    case "EditCount":
    				    hasEditCount = true;
    				    break;
    			    case "DisplayText":
    				    hasDisplayText = true;
    				    break;
    			    case "DisplayFlag":
    				    hasDisplayFlag = true;
    				    break;
    			    case "DisplaySequence":
    				    hasDisplaySequence = true;
    				    break;
    			    case "Description":
    				    hasDescription = true;
    				    break;
    		    }
    
    		    if (column.IsPrimaryKey)
    		    {
    			    pkType = GetPropertyType(column.SqlPropertyType);
    		    }
    	    }
    
    	    if (hasInserted && hasUpdated && hasInsertedBy && hasUpdatedBy && hasEditCount)
    	    {
    		    isAuditBase = true;
    		    return " : AuditBase<" + pkType + ">";
    	    }
    
    	    if (hasDisplayText && hasDisplayFlag && hasDisplaySequence && hasDescription)
    	    {
    		    isCodeTableBase = true;
    		    return " : CodeTableBase<" + pkType + ">";
    	    }
    
            return "";
        };
    
        // Writes any boilerplate stuff inside the POCO class
        Action<Table> WritePocoBaseClassBody = t =>
        {
            // Do nothing by default
            // Example:
            // WriteLine("        // " + t.ClassName);
        };
    
        Func<Column, string> WritePocoColumn = c =>
        {
            bool commentWritten = false;
            if ((Settings.IncludeExtendedPropertyComments == CommentsStyle.InSummaryBlock ||
                 Settings.IncludeComments == CommentsStyle.InSummaryBlock) &&
                !string.IsNullOrEmpty(c.SummaryComments))
            {
                WriteLine(string.Empty);
                WriteLine("        ///<summary>");
                WriteLine("        /// {0}", System.Security.SecurityElement.Escape(c.SummaryComments));
                WriteLine("        ///</summary>");
                commentWritten = true;
            }
            if (Settings.UseDataAnnotations)
            {
                if(c.Ordinal > 1 && !commentWritten)
                    WriteLine(string.Empty);    // Leave a blank line before the next property
    
                foreach (var dataAnnotation in c.DataAnnotations)
                {
                    WriteLine("        [" + dataAnnotation + "]");
                }
            }
    
            // Example of adding a [Required] data annotation attribute to all non-null fields
            //if (!c.IsNullable)
            //    return "        [System.ComponentModel.DataAnnotations.Required] " + c.Entity;
    
            return "        " + c.Entity;
        };
    
        Settings.ForeignKeyFilter = (ForeignKey fk) =>
        {
            // Return null to exclude this foreign key, or set IncludeReverseNavigation = false
            // to include the foreign key but not generate reverse navigation properties.
            // Example, to exclude all foreign keys for the Categories table, use:
            // if (fk.PkTableName == "Categories")
            //    return null;
    
    	    fk.IncludeReverseNavigation = false;
    
            // Example, to exclude reverse navigation properties for tables ending with Type, use:
            // if (fk.PkTableName.EndsWith("Type"))
            //    fk.IncludeReverseNavigation = false;
    
            return fk;
        };
    
        Settings.ForeignKeyProcessing = (foreignKeys, fkTable, pkTable, anyNullableColumnInForeignKey) =>
        {
            var foreignKey = foreignKeys.First();
    
            // If using data annotations and to include the [Required] attribute in the foreign key, enable the following
            //if (!anyNullableColumnInForeignKey)
            //   foreignKey.IncludeRequiredAttribute = true;
    
            return foreignKey;
        };
    
        Settings.ForeignKeyName = (tableName, foreignKey, foreignKeyName, relationship, attempt) =>
        {
            string fkName;
    
            // 5 Attempts to correctly name the foreign key
            switch (attempt)
            {
                case 1:
                    // Try without appending foreign key name
                    fkName = tableName;
                    break;
    
                case 2:
                    // Only called if foreign key name ends with "id"
                    // Use foreign key name without "id" at end of string
                    fkName = foreignKeyName.Remove(foreignKeyName.Length-2, 2);
                    break;
    
                case 3:
                    // Use foreign key name only
                    fkName = foreignKeyName;
                    break;
    
                case 4:
                    // Use table name and foreign key name
                    fkName = tableName + "_" + foreignKeyName;
                    break;
    
                case 5:
                    // Used in for loop 1 to 99 to append a number to the end
                    fkName = tableName;
                    break;
    
                default:
                    // Give up
                    fkName = tableName;
                    break;
            }
    
            // Apply custom foreign key renaming rules. Can be useful in applying pluralization.
            // For example:
            /*if (tableName == "Employee" && foreignKey.FkColumn == "ReportsTo")
                return "Manager";
    
            if (tableName == "Territories" && foreignKey.FkTableName == "EmployeeTerritories")
                return "Locations";
    
            if (tableName == "Employee" && foreignKey.FkTableName == "Orders" && foreignKey.FkColumn == "EmployeeID")
                return "ContactPerson";
            */
    
            // FK_TableName_FromThisToParentRelationshipName_FromParentToThisChildsRelationshipName
            // (e.g. FK_CustomerAddress_Customer_Addresses will extract navigation properties "address.Customer" and "customer.Addresses")
            // Feel free to use and change the following
            /*if (foreignKey.ConstraintName.StartsWith("FK_") && foreignKey.ConstraintName.Count(x => x == '_') == 3)
            {
                var parts = foreignKey.ConstraintName.Split('_');
                if (!string.IsNullOrWhiteSpace(parts[2]) && !string.IsNullOrWhiteSpace(parts[3]) && parts[1] == foreignKey.FkTableName)
                {
                    if (relationship == Relationship.OneToMany)
                        fkName = parts[3];
                    else if (relationship == Relationship.ManyToOne)
                        fkName = parts[2];
                }
            }*/
    
            return fkName;
        };
    
        Settings.ForeignKeyAnnotationsProcessing = (Table fkTable, Table pkTable, string propName) =>
        {
            /* Example:
            // Each navigation property that is a reference to User are left intact
            if (pkTable.NameHumanCase.Equals("User") && propName.Equals("User"))
                return null;
    
            // all the others are marked with this attribute
            return new[] { "System.Runtime.Serialization.IgnoreDataMember" };
            */
    
            return null;
        };
    
        // Return true to include this table in the db context
        Settings.ConfigurationFilter = (Table t) =>
        {
            return true;
        };
    
    	string GetPropertyType(string sqlType)
            {
                var sysType = "string";
                switch(sqlType)
                {
                    case "hierarchyid":
                        sysType = "System.Data.Entity.Hierarchy.HierarchyId";
                        break;
                    case "bigint":
                        sysType = "long";
                        break;
                    case "smallint":
                        sysType = "short";
                        break;
                    case "int":
                        sysType = "int";
                        break;
                    case "uniqueidentifier":
                        sysType = "System.Guid";
                        break;
                    case "smalldatetime":
                    case "datetime":
                    case "datetime2":
                    case "date":
                        sysType = "System.DateTime";
                        break;
                    case "datetimeoffset":
                        sysType = "System.DateTimeOffset";
                        break;
                    case "table type":
                        sysType = "System.Data.DataTable";
                        break;
                    case "time":
                        sysType = "System.TimeSpan";
                        break;
                    case "float":
                        sysType = "double";
                        break;
                    case "real":
                        sysType = "float";
                        break;
                    case "numeric":
                    case "smallmoney":
                    case "decimal":
                    case "money":
                        sysType = "decimal";
                        break;
                    case "tinyint":
                        sysType = "byte";
                        break;
                    case "bit":
                        sysType = "bool";
                        break;
                    case "image":
                    case "binary":
                    case "varbinary":
                    case "varbinary(max)":
                    case "timestamp":
                        sysType = "byte[]";
                        break;
                    case "geography":
                        sysType = Settings.DisableGeographyTypes ? "" : "System.Data.Entity.Spatial.DbGeography";
                        break;
                    case "geometry":
                        sysType = Settings.DisableGeographyTypes ? "" : "System.Data.Entity.Spatial.DbGeometry";
                        break;
                }
                return sysType;
            }
    
        // That's it, nothing else to configure ***********************************************************************************************
    
    
        // Read schema
        var factory = GetDbProviderFactory();
        Settings.Tables = LoadTables(factory);
        Settings.StoredProcs = LoadStoredProcs(factory);
    
        // Generate output
        if (Settings.Tables.Count > 0 || Settings.StoredProcs.Count > 0)
        {
    #>
    <#@ include file="EF.Reverse.POCO.ttinclude" #>
    <#  }
        if(Settings.GenerateSeparateFiles)
            GenerationEnvironment.Clear();#>
    
  • User Avatar
    0
    JeffMH created

    Well, hopefully that T4 template generates much more of the attributes needed so there won't be a need for the API. The system that I am using to generate it doesn't do terribly well at using data annotations so you have to use the API a little.

    One last question, then you can move on with your day....do you continue to use the T4 and not do code first? If yes, then you just use Code First for the ABP entities, then tie in your own Context for the other data?

    Again, appreciate the advice and help.

  • User Avatar
    0
    bbakermmc created

    We don't use code first. We have a separate context that we keep all our own models in. And we let ASPNetZero maintain its own context/models. Keeps things clean this way. Plus we use SSDTs to keep our DBs in line so its DBFirst. Also like I said, we use DevExtreme so the RadTool doesnt really work for us.

    Yes - I just started writing T4s this week to automate some of our development work. We are still on 4.6 and when we move to v5 I wanted to script out a bunch of things that we have learned along the way and get some stuff refactored and the code cleaned up. For us the T4s will be more of a starting point for new development, it will save a little time but honestly, you could do a lot of what the RadTools and T4 is doing by copy/paste/find/replace if your files are setup correctly. We dont have "simple" logic/tables so the T4s are just the basic template stuff so we can do more of the "real" work.

  • User Avatar
    0
    OutdoorEd created

    In working with an existing database for the MVC Jquery version I used Simon Hughes' EntityFramework Reverse POCO Generator in a separate project just to create the POCOs. One of the nice things in Simon's template is that you can control things like the namespace so even though it was in a separate project, I could generate the correct namespace for my project.

    I worked with a wonderful outside developer who laid out the architecture for this (just to admit that I am not smart enough to come up with this myself). Here is how one class was created for my Incident database application. It uses Repositories and separate Configuration files.

    I am only showing one database field from the table all the way through and don't show you any of the relationships to other tables to shorten the code. I used generic MVC scaffolding to create the skeleton of the Controller and all the CRUD Views and then replaced things in the Controller with the Repositories.


    FOLDER: OE_Tenant.Core\Incidents\Entity\IncidentFile.cs

    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.ComponentModel.DataAnnotations.Schema;
    using System.Data.Entity.Spatial;
    using Abp.Domain.Entities;
    using Abp.Domain.Entities.Auditing;
    

    namespace OE_Tenant.Incidents.Entity { [Table("idb_IncidentFile")] public partial class IncidentFile : FullAuditedEntity<Guid>, IMustHaveTenant { public int FileTypeId { get; set; } } }

    FOLDER: OE_Tenant.Core\Incident\Repos\IIncidentFileRepository.cs

    using Abp.Domain.Repositories; using OE_Tenant.Incidents.Entity; using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks;

    namespace OE_Tenant.Incidents.Repos { public interface IIncidentFileRepository : IRepository<IncidentFile, Guid> { } }

    FOLDER: OE_Tenant.EntityFramework\EntityConfigurations\IncidentFileConfiguration.cs

    using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.ModelConfiguration; using OE_Tenant.Incidents.Entity;

    namespace OE_Tenant.EntityConfigurations { public class IncidentFileConfiguration : EntityTypeConfiguration<IncidentFile> { public IncidentFileConfiguration() { // Primary Key this.HasKey(t => t.Id);

            // Table & Column Configuration
            this.ToTable("idb_IncidentFile");
            this.Property(t => t.Id).HasColumnName("Id");
            this.Property(t => t.FileTypeId).HasColumnName("FileTypeId");
            this.Property(t => t.TenantId).HasColumnName("TenantId");
        }
    }
    

    }


    FOLDER: OE_Tenant.EntityFramework\Repos\IncidentFileRepository.cs

    using OE_Tenant.EntityFramework.Repositories; using OE_Tenant.Incidents.Entity; using OE_Tenant.Incidents.Repos; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Abp.EntityFramework; using OE_Tenant.EntityFramework;

    namespace OE_Tenant.Repos { public class IncidentFileRepository : OE_TenantRepositoryBase<IncidentFile, Guid>, IIncidentFileRepository { public IncidentFileRepository(IDbContextProvider<OE_TenantDbContext> dbContextProvider) : base(dbContextProvider) { } } }


    FOLDER: OE_Tenant.EntityFramework\OE_TenantDbContext.cs

    using System.Data.Common; using System.Data.Entity; using Abp.Zero.EntityFramework; using OE_Tenant.Authorization.Roles; using OE_Tenant.Authorization.Users; using OE_Tenant.Chat; using OE_Tenant.Friendships; using OE_Tenant.MultiTenancy; using OE_Tenant.Storage; using System.Data.Entity.Core.Objects; using System.Data.Entity.Infrastructure; using EntityFramework.Functions; using OE_Tenant.Incidents.Entity; //Added for External Configuration Files using OE_Tenant.EntityConfigurations; //Added for Dynamic Filter using EntityFramework.DynamicFilters; using Abp.Domain.Entities;

    namespace OE_Tenant.EntityFramework { public class OE_TenantDbContext : AbpZeroDbContext<Tenant, Role, User> { public virtual DbSet<IncidentFile> IncidentFile { get; set; }

    public OE_TenantDbContext() : base("Default") { //Disable initializer to disable Migrations Database.SetInitializer<OE_TenantDbContext>(null); this.Configuration.LazyLoadingEnabled = false; this.Configuration.ProxyCreationEnabled = false; }

        public OE_TenantDbContext(string nameOrConnectionString)
            : base(nameOrConnectionString)
        {
            this.Configuration.LazyLoadingEnabled = false;
            this.Configuration.ProxyCreationEnabled = false;
        }
    
        public OE_TenantDbContext(DbConnection existingConnection)
            : base(existingConnection, false)
        {
            this.Configuration.LazyLoadingEnabled = false;
            this.Configuration.ProxyCreationEnabled = false;
        }
    
        public OE_TenantDbContext(DbConnection existingConnection, bool contextOwnsConnection)
            : base(existingConnection, contextOwnsConnection)
        {
            this.Configuration.LazyLoadingEnabled = false;
            this.Configuration.ProxyCreationEnabled = false;
        }
    
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            //Added - NEEDS TO BE IN TO PREVENT MUSTHAVETENANT ERROR
            base.OnModelCreating(modelBuilder);
    
            modelBuilder.Configurations.Add(new IncidentFileConfiguration());
    
         }
    }
    

    }


    FOLDER: OE_Tenant.Web\Areas\Incidents\Models\Dto\IncidentFileDto.cs

    using System; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Web.Mvc; using Abp.Application.Services.Dto; using Abp.AutoMapper; using OE_Tenant.Incidents.Entity;

    namespace OE_Tenant.Web.Areas.Incidents.Models.Dto { [AutoMapTo(typeof(IncidentFile))] [AutoMapFrom(typeof(IncidentFile))] public class IncidentFileDto : FullAuditedEntityDto<Guid> { [Display(Name = "File Type", Prompt = "Select the File Type")] [Required(ErrorMessage = "Please select a File Type")] public int FileTypeId { get; set; } } }


    FOLDER: OE_Tenant.Web\Areas\Incidents\ViewModels\IncidentFileViewModel.cs

    using System; using Abp.AutoMapper; using OE_Tenant.Incidents.Entity; using OE_Tenant.Web.Areas.Configuration.ViewModels;

    namespace OE_Tenant.Web.Areas.Incidents.ViewModels { [AutoMapFrom(typeof(IncidentFile))] [AutoMapTo(typeof(IncidentFile))] public class IncidentFileViewModel { public Guid Id { get; set; } public int FileTypeId { get; set; } public int TenantId { get; set; } } }


    FOLDER: OE_Tenant.Web\Areas\Incidents\Controllers\IncidentFileController.cs

    using System; using System.Collections; using System.Data.Entity; using System.Threading.Tasks; using System.Net; using System.Web.Mvc; using OE_Tenant.Incidents.Entity; using OE_Tenant.Web.Controllers; using Abp.Runtime.Validation; using OE_Tenant.Incidents.Repos; using Abp.Web.Mvc.Authorization; using OE_Tenant.Authorization; using OE_Tenant.Web.Extensions; using OE_Tenant.Web.Areas.Incidents.ViewModels; using OE_Tenant.Web.Areas.Incidents.Models.Dto; using Abp.AutoMapper; using OE_Tenant.Extensions; using System.Linq;

    namespace OE_Tenant.Web.Areas.Incidents.Controllers { [AbpMvcAuthorize(AppPermissions.Pages_Files)] public class FilesController : OE_TenantControllerBase { private readonly IIncidentFileRepository _repoIncidentFile; private readonly ILkpFileTypeRepository _repoLkpFileType;

        public FilesController(
            IIncidentFileRepository repoIncidentFile,
            ILkpFileTypeRepository repoLkpFileType
        )
        {
            _repoIncidentFile = repoIncidentFile;
            _repoLkpFileType = repoLkpFileType;
        }
    
        [AbpMvcAuthorize(AppPermissions.Pages_Files_Index)]
        // GET: Incidents/IncidentFiles
        public ActionResult Index()
        {
            return View();
        }
    
        [AbpMvcAuthorize(AppPermissions.Pages_Files_Details)]
        // GET: Incidents/IncidentFiles/Details/5
        public async Task&lt;ActionResult&gt; Details(Guid? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            IncidentFile incidentFile = await _repoIncidentFile.GetAllIncluding(i => i.LkpFileType).SingleOrDefaultAsync(i => i.Id == id.Value);
    
            if (incidentFile == null)
            {
                return HttpNotFound();
            }
    
            var model = incidentFile.MapTo&lt;IncidentFileDto&gt;();
    
            return View(model);
        }
    
        [AbpMvcAuthorize(AppPermissions.Pages_Files_Create)]
        // GET: Incidents/IncidentFiles/Create
        public async Task&lt;ActionResult&gt; Create()
        {
            ViewBag.FileTypeId = new SelectList(await _repoLkpFileType.GetAllListAsync(), "Id", "FileType");
            return View();
        }
    
        // POST: Incidents/IncidentFiles/Create
        [DisableValidation]
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task&lt;ActionResult&gt; Create(IncidentFileDto model)
        {
            if (ModelState.IsValid)
            {
                var incidentFileEntity = model.MapTo&lt;IncidentFile&gt;();
                await _repoIncidentFile.InsertAsync(incidentFileEntity);
                return RedirectToAction("Index");
            }
           ViewBag.FileTypeId = new SelectList(await _repoLkpFileType.GetAllListAsync(), "Id", "FileType");
            return View(model);
        }
    
        [AbpMvcAuthorize(AppPermissions.Pages_Files_Edit)]
        // GET: Incidents/IncidentFiles/Edit/5
        public async Task&lt;ActionResult&gt; Edit(Guid? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
    
            IncidentFile incidentFile = await _repoIncidentFile.GetAsync(id.Value);
    
            if (incidentFile == null)
            {
                return HttpNotFound();
            }
    
            ViewBag.FileTypeId = new SelectList(await _repoLkpFileType.GetAllListAsync(), "Id", "FileType", incidentFile.FileTypeId);
            var model = incidentFile.MapTo&lt;IncidentFileDto&gt;();
    
            return View(model);
        }
    
        // POST: Incidents/IncidentFiles/Edit/5
        [DisableValidation]
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task&lt;ActionResult&gt; Edit(IncidentFileDto model)
        {
            if (ModelState.IsValid)
            {
                IncidentFile incidentFile = await _repoIncidentFile.GetAsync(model.Id);
    
                incidentFile.FileTypeId = model.FileTypeId;
    
                await _repoIncidentFile.UpdateAsync(incidentFile);
                return RedirectToAction("Index");
            }
    
            ViewBag.FileTypeId = new SelectList(await _repoLkpFileType.GetAllListAsync(), "Id", "FileType", model.FileTypeId);
            return View(model);
    
        }
    
        [AbpMvcAuthorize(AppPermissions.Pages_Files_Delete)]
        // GET: Incidents/IncidentFiles/Delete/5
        public async Task&lt;ActionResult&gt; Delete(Guid? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
    
            IncidentFile incidentFile = await _repoIncidentFile.GetAllIncluding(i => i.LkpFileType).SingleOrDefaultAsync(i => i.Id == id.Value);
    
            if (incidentFile == null)
            {
                return HttpNotFound();
            }
    
            var model = incidentFile.MapTo&lt;IncidentFileDto&gt;();
    
            return View(model);
    
        }
    
        // POST: Incidents/IncidentFiles/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public async Task&lt;ActionResult&gt; DeleteConfirmed(Guid id)
        {
            await _repoIncidentFile.DeleteAsync(id);
            return RedirectToAction("Index");
        }
    
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                //db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
    

    }