0

I don't have much experience of C# & Database. My chef engineer has built tables in a database. In C# code he has built a class for each table with all the information that is already in the database table (see code extract). I am wondering if this is good practice and if there isn't a proper and easier way to have table information in one place. Are there easy to use tools that can create a table class out of a table definition? Is something built in Visual Studio? Also he programmed stored procedures for each table to access or store one row. So if there would be a future change in the schema (one row of a table), this demands altering three different parts. I wonder if this is good practice.

Class code extract:

public class Users: DataObjectBase
{
    #region Ctor
    public Users(string connString) : base()
    {
        _objName = "Users";
        _connectionString = connString;

        _columnNames = new string[] { "UserID", "FirstName", "LastName", "LoginName", "PWHash", "MediaID", "IsActive" };
        _columnSqlTypes = new SqlDbType[] { SqlDbType.Int, SqlDbType.NVarChar, SqlDbType.NVarChar, SqlDbType.NVarChar, SqlDbType.NVarChar, SqlDbType.BigInt, SqlDbType.Bit };
        _columnTypes = new string[] { "System.Int32", "System.String", "System.String", "System.String", "System.String", "System.Int64", "System.Boolean"};
        _columnSizes = new int[] { 4, 100, 100, 100, 40, 8, 1 };
        _fieldCount = 7;
        base.Initialize();
        //("Users", connString);
    }

.... I want to learn doing it the proper way. Please describe it easy, as I don't understand some technical terms yet. Thanks for your patience and any hints or reccomondations.

To built a database application and learning to handle database tables efficiently.

DataSalad
  • 11
  • 2
  • 3
    There are tools that are a lot better than this approach. Search for [ORM](https://en.wikipedia.org/wiki/Object%E2%80%93relational_mapping) like EntityFramework or Dapper – Steve Jul 06 '23 at 10:11
  • 2
    Your _Chef Engineer_ seems stuck in the year 2005, it seems. – Dai Jul 06 '23 at 10:12
  • 1
    To be honest my Chef Engineer is great for Beef Wellington but not so great at coding. – Stu Jul 06 '23 at 10:20
  • @Stu I think the term is bakineering. Too bad Baking Impossible got cancelled – Panagiotis Kanavos Jul 06 '23 at 10:23
  • @Dai not even. NHibernate was alive and well back then even if a "bit" verbose. In fact, there were a *lot* of competing ORMs back then – Panagiotis Kanavos Jul 06 '23 at 10:24
  • 1
    @DataSalad for starters check [Dapper](https://github.com/DapperLib/Dapper) for starters. In *a single line of code* it will parameterize and execute a query and map the results to objects. It can execute stored procedures too. There are some helper libraries to construct queries or insert objects directly to tables, but its main strength is that it can work just with the query, the parameter values and a type to map to – Panagiotis Kanavos Jul 06 '23 at 10:28
  • Fully agree with @PanagiotisKanavos Dapper is simpler, faster and doesn't require a lot of plumbing – Steve Jul 06 '23 at 10:30
  • @DataSalad at the other end of the ORM spectrum, [Entity Framework Core](https://learn.microsoft.com/en-us/ef/core/) will map tables to objects, generate queries, joins etc and generally try to give the impression of working with in-memory objects instead of tables and rows. It also manages transactions so you don't have to, but you do need to understand its logic. – Panagiotis Kanavos Jul 06 '23 at 10:31
  • Thank you already for all your comments and assessments. Can you reccomend a godd tutorial for dapper? I have heared of Entity Framework. How complicated is it to learn the necessary things to get it running? – DataSalad Jul 06 '23 at 11:03
  • @DataSalad, just google for dapper tutorials and even on youtube. It is very easy to use and fast. Likely you can learn it in an hour or two. EF is easy to use as well. You can check its tutorials directly on MS Learn site: https://learn.microsoft.com/en-us/aspnet/entity-framework – Cetin Basoz Jul 06 '23 at 12:22

1 Answers1

0

Actually your chef engineer have been used Database-first approach , but it is not advisable to use as if we need to change the schema , we would face difficulties , instead you can use code-first approach here. We will be writing the C# class which is called as 'Model' for example

public class StudentDetails
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string City {get ; set; }

}

If you need to add primaryKey or ForeignKey , you can use annotation like [PrimaryKey], [ForeignKey] as mentioned below.

  public class StudentDetails
{
    [PrimaryKey]
    public int Id { get; set; }
    [ForeignKey]
    public string Name { get; set; }
    public string City {get ; set; }

}

After creating this Class in Model Folder, then you need to create a dbContext file then add the following lines of code in it

public class ApplicationDbContext : DbContext
    {
        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
        {
            
        }
      
        public DbSet<RegisterUser> UserAccoutDetails { get; set; }
}

Every model created should be updated in the dbContext file.After adding DbSet then you need to migrate to database, for migration you need to execute the following code in Terminal

Add-migration InitialMigration

InitialMigration is a name given to my migrationfile, after executing the above line , a folder called Migration will be generated . Now the model will not be not updated in database , to update u need to execute the below line.

update-database

now you could see the table will created in database. This approach is advisable , because if you need to add a column to the table in database , you need to just add the column name in the model then again execute the migration line , now you should change the migration file name and after executing it then execute the update-database , now you check the table in the database , it will be updated.

  • You'll get into *more* trouble if you modify the class then try to apply the changes to the production database. You'll have to migrate the existing data to the new schema, something complex and possibly expensive. Migrations aren't a production deployment tool, they're meant to make development easier. – Panagiotis Kanavos Jul 06 '23 at 11:27
  • @KAVIN S CSE your code and example code refers to using Entity Framework? what you mean with "execute the following code in Terminal"? Which Terminal? – DataSalad Jul 06 '23 at 11:42
  • Yes, he refers to using Entity Framework. Terminal is one of the windows you can open via the "View" menu of Visual Studio. – Mike Nakis Jul 06 '23 at 12:11