Working with BigInteger with C# .Net and Sql Server

If you must pass to a Store Procedure or just for a simple query a variable of type BigInt beware you can be surprised with the result. BigInt in SqlServer has nothing to do with the BigInteger class of .Net. BigInt in Sql exists a long way before BigInteger from .Net (4.0). If you are using BigInteger you will get a System.InvalidCastException.

An exception of type ‘System.InvalidCastException’
occurred in System.Data.dll but was not handled in user code

Additional information: Failed to convert parameter
value from a BigInteger to a Int64.

To pass a value to Sql Server of type BigInt, you must use a long in .Net.

For example, here is how to pass a long to SqlServer using SqlParameter.

long myBigNumber = 1;
var myParameter = new SqlParameter("@myParameterName", myBigNumber) 
                  { SqlDbType = SqlDbType.BigInt };

You have to use a long for the value, but you specify the type to be of SqlDbType.BigInt. Has you can see, we do not need to specify the DbType but only the SqlDbType. We are using a long because a long and Int64 is the same type.

Entity Framework Disconnected Graph and the root

Entity Framework works with entities that can be attached or not. Attached entities are tracked by Entity Framework. This way, Entity Framework can detect if a change has been made or if something has been deleted. Having an entity not loaded from Entity that exist inside the database is called a disconnect entity. When persisting object into Entity Framework, we are working with graph. This mean that an entity has other reference to entities which can also have other entities. The entity that we are performing an operation on is the root of the graph. Depending of the situation, the root can change. For example, you can have E1 referencing E2 which reference E3. If you are using E2 to do some operation, the root is E2. It is important to understand what is the root because operation executed on the root can have side effect on the rest of the graph.

A simple example is this one. You have an entity that has a list of another type of entities. If you instantiate this entity and add to its list some entities and only do a Context.Add to the root, all entities from the added entity will be also added.

using (var context = new YourContext())
{
    var newHouse = new House {Address = new Address{City="TestCity",Number = 123,Street="Street Name here"}};
    newHouse.Owner = new Person {Name = "Automatically added from the property", BirthDate = DateTime.Now};
    newHouse.Resident = new Collection<Person>(new []{new Person{BirthDate = DateTime.Now,Name = "Automatically added from the collection"}});
    context.Houses.Add(newHouse);
    context.SaveChanges();
}

In this example, all Person entity does not exist in the database. The House entity does not exist. Rather to add the House entity and all Person, we just need to add the root element: the House. This is what the code is doing. This execution produces three entries into the database : one for the House, one for the Owner (a Person) and a last one for the Resisdent (a Person).

DatabaseRootAdd

It is important to notice that Entity Framework is enough bright to no mark a children as “Added” if this one is already been tracked by its context. For example, you load from the database a Person entity and add it to the collection. This one will not be added but will be attached.

You can find this example on GitHub or in this Zip File.

Entity Framework Create Entity

Creating a new instance and having Entity Framework handling this one in its context require some manipulations. You have two different paths to accomplish this goal. The first one is to create the entity and to add them to the DbSet. The second one is to create the instance from the DbSet directly instead of instantiated this one with new keyword.
Here is a code that add two entities. One that is not tracked by Entity Framework and when that it is because it has been created with the Create method.

using (var context = new YourContext())
{
    // Create a new instance with Add
    var person = new Person {Name = "New person with New Keyword",BirthDate = DateTime.Now};
    Console.WriteLine("Person non-proxy state: " + context.Entry(person).State);
    context.Persons.Add(person);// Now Entity Framework added the object but was not tracking anything

    // Create a new instance with Entity Framework (proxy)
    var person2 = context.Persons.Create();
    Console.WriteLine("Person proxy state: " + context.Entry(person2).State);
    person2.Name = "New Person from EF";
    person2.BirthDate = DateTime.Now;
    context.Persons.Add(person2); // Still need to add but EF was tracking changes
    var x1 = context.Persons.Local.Count();
    Console.WriteLine("The count is at " + x1);

    // Detect Changes
    context.ChangeTracker.DetectChanges();
    Console.WriteLine("Person non-proxy state: " + context.Entry(person).State);
    Console.WriteLine("Person proxy state: " + context.Entry(person2).State);
    var x2 = context.Persons.Local.Count();
    Console.WriteLine("The count is at " + x2);

    context.SaveChanges();
}

The result is the same for those two creations because we do not use anything from the Entity Framework Proxy. Choosing from one or the other method to create is more a preference than a guidance. You have to choose which one you prefer and keep your whole system using the same. Otherwise, it will be confusing to know if we need to or not bound the entity to EF proxies.

ProxyNonProxyCreate

You can get the source code on GitHub or download the Zip file.

Asp.Net MVC @: vs text tag vs Html.Raw

Asp.Net MVC offers several ways to output Html from a Razor page, also know as a .cshtml page or the view.

The first way is to use the syntax shortcut @:. This indicate to MVC that the rest of the line is a content block. The advantage of this way to output is that Visual Studio handles closing and opening tag and will continue to work by showing you if a closing tag is missing. The disadvantage is that you cannot use this for Html tag that is over multiple lines.

The second way is the text tag. Very similar to the shortcut syntax but this time it goes on several line.

<text>
This is super to output something like the date : @DateTime.Now
</text>

Finally, you can use the Html Helper .Raw. You have to remember that the helper return a HtmlString. This require you to use the @ before the Html Helper. Otherwise, the method will return the value but nothing will be rendered.

@Html.Raw("<div>It works</div>")
Html.Raw("<div>This does not work</div>")

If you are within a multi-statement block @{…} and that you want to output Html than you have all three choices. The first one is the @: and the second is the Html Helper Raw.

 <div class="row">
            @{
                foreach (var contest in Model.SubscribedContests)
                {
                    if (iSubScribe != 0 && iSubScribe % itemPerColumnSubScribe == 0)
                    {
                        @Html.Raw("</div>");
                        @:</div>
                    }
                }
             }
</div>

As you can see, the two closing divisions are legal. Both output the div html tag. You cannot use directly the html because it expects to have C# code. Visual Studio will not be able to resolve the Html.

The rules of thumb is that if you need to output Html content to the browser to have this one interpreted it, than you need to send non-encoded html, which require to send “raw” html. Otherwise, you should always send html encoded element which is more safe. This is the default behavior because it protects you to have user trying to embedded undesirable html in your web page.