Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>As I've written in my comment, you should simply go for a <a href="http://en.wikipedia.org/wiki/Object-relational_mapping" rel="nofollow">Object-Relational Mapping</a> framework, since you are obviously trying to abstract the mapping from your domain into the database.</p> <p>That being said, you can generalize the whole thing using Reflection. Provided that you don't intend to add complex mapping rules, you would have something similar to:</p> <pre><code>foreach (var propertyInfo in myClass.GetType().GetProperties()) { var name = propertyInfo.Name; var value = propertyInfo.GetValue(myClass); // do stuff Console.WriteLine("Value of {0} is {1}", name, value ?? "null"); } </code></pre> <p>A proper ORM does a lot more than this. If allows you to define specific mapping rules for each property. Nested objects and automatic mapping of one-to-many relations. It does lots of complex caching to avoid performance penalty associated with reflection (and more important, database access). It allows lazy access to the database by deferring queries until data is needed. It tracks which properties are changed and automatically updates them. And all that by including a reference to a library, spending a day or two looking at examples (and asking stuff on Stack Overflow) and writing a mapping configuration file. </p> <p>Or, you can define <a href="https://github.com/jagregory/fluent-nhibernate/wiki/Getting-started" rel="nofollow">mappings through code</a> to get full intellisense and better type safety:</p> <pre><code>// fluent nhibernate example public class CatMap : ClassMap&lt;Cat&gt; { public CatMap() { // define which properties are going to be saved, and how Id(x =&gt; x.Id); Map(x =&gt; x.Name).Length(16).Not.Nullable(); Map(x =&gt; x.Sex); References(x =&gt; x.Mate); HasMany(x =&gt; x.Kittens); } } </code></pre> <p>What you are doing right now is a maintenance nightmare. You are enforcing a rule where each data class needs to expose its properties as an object array (and think about how you would <em>update</em> their values this way). Also, you lose all type safety because you end up with plain objects. The only way for you to know which property you are accessing is by the index of the <code>loop</code> array, meaning you are going for lots of <code>if</code> conditions and magic numbers all over your code. As an exercise of how things shouldn't be done, it's fine, but don't allow this to end up in production code or you will spend countless hours fixing bugs and changing code to add new functionality.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload