HiveBrain v1.2.0
Get Started
← Back to all entries
principlecsharpMinor

Code First approach, feeding the table

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
thefeedingfirstcodeapproachtable

Problem

I have a database (PostgreSQL) from which I want to migrate some data to a MS SQL Server database. I decided to use a code first approach. The question is related to the proper way of feeding my new tables.

Model.cs:

public class Info 
{
    [Key]
    public int InfoID { get; set; }   
    public int NameID { get; set; }    
    public string Name { get; set; }
}


DatabaseInitializer:

private void SeedInfos(SomeContext context)
    {
        var Infos = new List();

using (var com = new NpgsqlCommand(PostgresSQLs.GetAllInfos, EstablishedConnection()))
        {
            using (var r = com.ExecuteReader())
            {
                while (r.Read())
                {
                    Infos.Add(new Info { InfoID= Convert.ToInt32(r["infoID"]), NameID = Convert.ToInt32(r["NameId"]), Name = r["Name"].ToString()});
                };
            }
        }
        foreach (var Usr in Users)
            context.Infos.Add(Usr);
    }


One of my concerns is related to the static class PostgreSQL where I store queries which are retrieving the data I need from PostgreSQL. Is it a proper approach? The more complicated query, the more complex code, so it may be hard to maintain later, isn't it? What approach would you use?

Besides, such data feeding may cost a lot of memory in case the table is big. Is there a possibility to avoid memory leaks?

Solution

Variables should be named using camelCase casing, see the NET naming guideline so Infos -> infos and Usr -> usr but as one shouldn't use abbreviation for any names you should change it to users which is much easier to read. This same rule applies to r vs reader and com vs command.

Using braces {} always although they might be optional is the way to make your code less error prone.

foreach (var user in Users)
{
    context.Infos.Add(user);
}


I don't know where these Users are coming from and what context.Infos type is, but if it is by any chance a List you could use the AddRange() method to add them all at once like context.Infos.AddRange(Users);.

What sense does it have to fill a List which is not used afterwards ?

Having a static class containing the queries can be ok, but you should at least add some possibility to add custom queries as well.

Code Snippets

foreach (var user in Users)
{
    context.Infos.Add(user);
}

Context

StackExchange Code Review Q#114171, answer score: 7

Revisions (0)

No revisions yet.