C# static database class? - c#

I have a Database class which contanins the follwing methods:
public bool ExecuteUDIQuery(string query) // UDI = Update Delete Insert
public bool ExecuteSelectQuery(string query)
public bool ExecuteSP(string sp, string[,] parms)
public int ExecuteSPReturnValue(string sp, string[,] parms)
The results of the methods are stored in private datasets or datatables. These objects are defined as getters.
There're about 10 classes which use the Database class. Every class creates an object of the class Database. Now i was thinking to make the Database class static. Is this a good idea? If so, why? Of not, why not?

If I understand, the database class has some properties that store the result of the query? If so, you cannot make them static, since that is not thread-safe. If the result of a query is stored in these properties, what would happen if a second query would execute right after the first? It would be stored in the same static variable. The same goes for a web application: the result of another user browsing the site would change the results of the first user.
EDIT: To summarize, do NOT make the class static when you store the result of the queries in static variables, especially not when the class is used in a website, as the properties value will be shared amongst all visitors of your website. If 20 visitors do a query at the same time, visitor 1 will see the results of visitor 20's query.

In your specific example, I'd advise against making the class static: you're keeping state in the Database class, and by making the class static, that state will be shared amongst all classes using your Database. In your current setup, each Database instance keeps its own state, so there's no problem with Database calls interfering with each other.
If you'd refactor the Database class to return the datasets when doing a method call, you'd be fine making it static: there would be no stateful information left in the Database class.
But since this is not the case: no, don't make the class static.

In addition to the others comments about thread safety there is also the issue of paralellization. In your case you won't be able to open several connections to the database at the same time and you won't be able to perform multiple paralell queries, even if thread safety of the results isn't an issue.
So I agree with the others, don't make a static class out of it.
Making the class static may be convenient, but creating new instances of it probably won't be an expensive operation so there probably isn't much to gain performance-wise either.
Edit:
I saw in a comment that you want to use your class on a web site. In that case you REALLY shouldn't do this. With a static database class you will only be able to safely serve one request at any time, and that is not what you want.

It depends on what kind of database or ORM that you're using. But in my experience it's seemed like a good idea but ended up shafting me. Here's how it did for me in LINQ-to-SQL:
I had a repository class that had a static variable to a data context. It worked at first, but when I had to make many more repository classes I ended up getting bugs as I hacked along. It turns out that data context in LINQ-to-SQL caches up all results and there is no way to refresh them. So if you added a post in a table in one context, it won't show up in other that cached that table. The solution was to remove the static modifier and let the repository create the context in the constructor. Since the repository classes were constructed as they were used, so would a fresh new data context.
You could argue that static variables leaves less footprint in memory, but the footprint for a data context is quite small to begin with and will be garbage collected in the end.

Contrary to the answer post.
I've built a webframework with a static database access it works great and gives great performance.
You can check out the source code at http://www.codeplex.com/Cubes

If you are just executing queries against the DB, then yes make it static. You only have to create an instance if this object needs to keep some sort of state.

If you have a static method you need to keep track of instances when you open and close the database.
So what you probably want to do is have a static Method called instance or current instance. And within you create a new instance of your db-class returning it in the static method.

Your methods good for static usage. I think, you have no trouble to convert them to static methods for now.
but later maybe you will need to manage transaction. leaving the transaction management to a class is saves lots of time I think. and this scenario is best fits with a nonstatic class.

Related

Using Entity Framework to return a table of data to iterate against

I am currently using EF 6 to do the following. Execute a stored procedure, then bring in the data I need to use. The data is usually 30-40 rows per application run.
I then iterate over the var, object, table (whatever you would like to call it), performing similar (sometimes different) tasks on each row. It works great. I am able to create an Entity object, expose the different complex functions of it, and then create a var to iterate over.
Like:
foreach (var result in StoredProcedureResult)
{
string strFirstname = result.FirstName
string strLastName = result.LastName
//more logic goes here using those variables and interacting with another app
}
I recently thought it would be cool if I had a class solely for accessing the data. In this way, I could just reference that class, toss the corresponding connection string into my app.config, and then I can keep the two sets of logic separate. So when attempting to do the above in that structure, I get to the point at which, you can't return a var, or when I attempt to match object return type. The return type of the execution of a stored procedure is object (which I can't iterate on).
So my question is, how does one get to the above example, except, the var result, get returned from this data access class?
If I am missing something, or its not possible because I am doing this incorrectly, do let me know. It appeared right in my head.
I'm not going to describe the architecture in full. But based on your comments you can do the following (this is not the definitive nor the only way how to do it):
in your data access project you keep the DBContext class, all the code for the stored procedure call and also the class that defines the result of the SP call, let's call it class A;
in your shared layer project - I would suggest calling it Service layer - you can create a XYService class, that has a method e.g. GetListOfX that connects to the DB and calls the procedure, if needed this method can also perform some logic, but more importantly: it doesn't return class A, but returns a new class B (this one is defined in the service layer, or can be defined in yet another project - that might be the true shared/common project; as it would be just a definition of common structures it isn't really a layer);
in your application layer you work only with the method GetListOfX of the XYService and the class B, that way you don't need a reference to the data access project
In a trivial case the class B has the same properties as the class A. But depending on your needs the class B can have additional properties/functionality it can also ignore some properties of A or even combine multiple properties into one: e.g. combining the FirstName and LastName as one property called simply Name.
Basically what you are looking for is the multi-tier application architecture (usually 3-4 tier). The full extent of such approach (which includes heavy usage of concepts like interfaces and dependency injection) might not be suitable or needed based on your goals, e.g. if you are building just a small application for yourself with a couple of functions or you know there won't be any reuse of the components of the final solution, then this approach is too wasteful and you can work faster with everything in one project - you should still apply principles like SOLID, DRY and Separation of concerns.

Best practice lookup-tables (GetOrCreate)

First I want to explain my situation in a few sentences:
- I have a number of, what I call them, lookup-tables. This means I want all values in there to be unique. For example a lookup-table for CPU models with a name and a GUID.
public partial class CPUModel : EntityObject
{
public Guid Id {}
public String Name{}
}
The entities are safed in a SQL CE database with the help of Entity Framework and C#
I have made a CRUDManager which helps me to Select, Insert, Update and Delete Entities.
All these Operations work with a ReaderWriterLockSlim to secure against problems with multithreading.
Now there should be some sort of GetOrCreate Method where I can say GetOrCreate(cpuModelName) and this gives me a saved CPUModel, either already existing or new created. This method should also work with the ReaderWriterLockSlim.
So I would want to implement this method on CRUDManager.
Do you think I'm on the right track or would you place this directly on the CPUModel (or even somewhere else?
Thank you very much :)
CRUDManager is a good place for it. I would just look the value up (ideally via a Lookup() type function, and if it exists, select it. If not, call Create() or whatever function you have defined to create it.
It sounds like you want a dictionary. I recommend reading about it here.

Should I encapsulate the update method inside of object or have method which accepts an object to update?

I actually have 2 questions related to each other:
I have an object (class) called, say MyClass which holds data from my database. Currently I have a list of these objects ( List < MyClass > ) that resides in a singleton in a "communal area". I feel it's easier to manage the data this way and I fail to see how passing a class around from object to object is beneficial over a singleton (I would be happy if someone can tell me why). Anyway, the data may change in the database from outside my program and so I have to update the data every so often. To update the list of the MyClass I have a method called say, Update, written in another class which accepts a list of MyClass. This updates all the instances of MyClass in the list.
However would it be better instead to encapulate the Update() method inside the MyClass object, so instead I would say:
foreach(MyClass obj in MyClassList) {
obj.update();
}
What is a better implementation and why?
The update method requires a XML reader. I have written an XML reader class which is basically a wrapper over the standard XML reader the language natively provides which provides application specific data collection. Should the XML reader class be in anyway in the "inheritance path" of the MyClass object - the MyClass objects inherits from the XML reader because it uses a few methods. I can't see why it should. I don't like the idea of declaring an instance of the XML Reader class inside of MyClass and an MyClass object is meant to be a simple "record" from the database and I feel giving it loads of methods, other object instances is a bit messy. Perhaps my XML reader class should be static but C#'s native XMLReader isn't static?
Any comments would be greatly appreciated.
For your first question, I would suggest putting an update method in MyClass. It sounds like you may be instantiating multiple copies of the same object, and perhaps a better solution would be to update the original MyClass objects directly through their update methods.
This would also give you the added advantage of being able to update individual objects in the future and should be more maintainable.
For your second question, it sounds like MyClass contains data from a database, making it an entity object. Entity objects shouldn't contain business logic, so I think you'd be okay having a Service class use the XMLReader to perform operations on the data and then use the getters/setters to manipulate the data in the object. Same as before, this has the advantage of keeping your code loosely coupled and more maintainable.
Do not include Update() within the class. I know it seems tempting because it the update call "easier" but what that would be creating dependencies. (Presumably) MyClass contains db data because it is a domain object which is represents the state of some real world "unit" (tangible, conceptual, or otherwise). If you include an update() method; now you're domain object is not only responsible for representing the state of some logical "thing", but it is also responsible for persistence logic (save, load, new, delete). You'd be better off creating a service which handles those responsibilities. This relates to the design principle of high cohesion, ie. each class has only 1 responsibility (or type of responsibility at least). eg.... persistenceService.saveUser(myUser);
This is basically the same question, except now you are talking about making your class directly dependant (as a descendant in this case) of a specific type of persistence (writing to xml file) which is even worse than having your class be dependent on persistence in a more generalized way.
Think about it like this when trying to make design decisions... plan on change (instability, chaos, or whatever you would like to call it). What if a month from now you need to switch out the XML persistance for a database? Or what if you all of a sudden have to deal with MyClassVariantA, MyClassVariantB, MyClassVariantC? By minimizing dependencies, when you do have to change something it won't necessitate a cascade of changes throughout every other part of your application.

should I make this class static?

In the projects I worked on I have classes that query/update database, like this one,
public class CompanyInfoManager
{
public List<string> GetCompanyNames()
{
//Query database and return list of company names
}
}
as I keep creating more and more classes of this sort, I realize that maybe I should make this type of class static. By doing so the obvious benefit is avoid the need to create class instances every time I need to query the database. But since for the static class, there is only one copy of the class, will this result in hundreds of requests contend for only one copy of static class?
Thanks,
I would not make that class static but instead would use dependency injection and pass in needed resources to that class. This way you can create a mock repository (that implements the IRepository interface) to test with. If you make the class static and don't pass in your repository then it is very difficult to test since you can't control what the static class is connecting to.
Note: The code below is a rough example and is only intended to convey the point, not necessarily compile and execute.
public interface IRepository
{
public DataSet ExecuteQuery(string aQuery);
//Other methods to interact with the DB (such as update or insert) are defined here.
}
public class CompanyInfoManager
{
private IRepository theRepository;
public CompanyInfoManager(IRepository aRepository)
{
//A repository is required so that we always know what
//we are talking to.
theRepository = aRepository;
}
public List<string> GetCompanyNames()
{
//Query database and return list of company names
string query = "SELECT * FROM COMPANIES";
DataSet results = theRepository.ExecuteQuery(query);
//Process the results...
return listOfNames;
}
}
To test CompanyInfoManager:
//Class to test CompanyInfoManager
public class MockRepository : IRepository
{
//This method will always return a known value.
public DataSet ExecuteQuery(string aQuery)
{
DataSet returnResults = new DataSet();
//Fill the data set with known values...
return returnResults;
}
}
//This will always contain known values that you can test.
IList<string> names = new CompanyInfoManager(new MockRepository()).GetCompanyNames();
I didn't want to ramble on about dependency injection. Misko Hevery's blog goes into great detail with a great post to get started.
It depends. Will you ever need to make your program multithreaded? Will you ever need to connect to more than one database? Will you ever need to store state in this class? Do you need to control the lifetime of your connections? Will you need data caching in the future? If you answer yes to any of these, a static class will make things awkward.
My personal advice would be to make it an instance as this is more OO and would give you flexibility you might need in the future.
You have to be careful making this class static. In a web app, each request is handled on its own thread. Static utilities can be thread-unsafe if you are not careful. And if that happens you are not going to be happy.
I would highly recommend you follow the DAO pattern. Use a tool like Spring to make this easy for you. All you have to do is configure a datasource and your DB access and transactions will be a breeze.
If you go for a static class you will have to design it such that its largely stateless. The usual tactic is to create a base class with common data access functions and then derive them in specific classes for, say, loading Customers.
If object creation is actually the overhead in the entire operation, then you could also look at pooling pre-created objects. However, I highly doubt this is the case.
You might find that a lot of your common data access code could be made into static methods, but a static class for all data access seems like the design is lost somewhere.
Static classes don't have any issues with multi-threaded access per-se, but obviously locks and static or shared state is problematic.
By making the class static, you would have a hard time unit testing it, as then you
would probably have to manage internally the reading of the connection string in a non-clear manner, either by reading it inside the class from a configuration file or requesting it from some class that manages these constants. I'd rather instantiate such a class in a traditional way
var manager = new CompanyInfoManager(string connectionString /*...and possible other dependencies too*/)
and then assign it to a global/public static variable, if that makes sense for the class, ie
//this can be accessed globally
public static CompanyInfoManager = manager;
so now you would not sacrifice any flexibility for your unit tests, since all of the class's dependencies are passed to it through its constructor

Nested Database transactions in C#

I have a base class that declares a private non-static reference to the DataBase Handler instance (DBH).
DBH is a class we use to simplify database operations of derived classes. It contains the usual methods, like ExecuteScalar, StartTransaction among others; and it provides additional benefits in the application context, like caching and zero configuration.
Instances of derived classes use DBH to read/save its state in the database, and since their operations are not atomic, all derived classes use this transaction. Everything is going on in one place: a virtual method called InsertUpdate() declared in the base class.
Next, I have a collection (called Book) of instances of derived classes. I want to take collection updates as transaction.
I want to achieve something similar to this:
DatabaseHandler dbh = new DatabaseHandler()
t = dbh.StartTrasaction();
foreach( Type o in Book<Type> )
{
o.prop1 = ..
o.prop2 = ...
o.method1() ...
o.InsertUpdate(t); // uses its own instance of DatabaseHandler and starts its own transaction
}
dbh.EndTransaction(t);
Currently the InsertUpdate method is parameter-less. I guess I'll have to introduce an overloaded version which accepts a transaction object.
Besides solving my current issue, are there any design issues I need to know about? How can I improve this design or institute a better design?
Make sure you read this question
Personally, I usually go with "my own" implementation of a TrasactionScope like object that wacks data on to TLS with the added benefit of having a factory that allows for easy profiling and logging.
To me your current design sound fairly complex. By decoupling your raw database access code from your classes it will reduce duplication (and avoid requiring all your data access classes inherit off a base class). Defining an object as opposed to a set of static methods for DB access will ease testing (you can substitute a mock class)
Have you looked at the System.Transactions namespace? Unless you have already discounted it for some reason you may be able to leverage the built in nested transaction support provided there - e.g:
using (var scope = new TransactionScope())
{
// call a method here that uses a nested transaction
someObject.SomeMethodThatAlsoUsesATransactionScope();
scope.Complete();
}
If the updates are all happening on the same database connectino, then the nested transactions will work as expected. Each InsertUpdate() will run its own transaction, with the overall transaction on dbh being able to roll back the entire thing.

Categories

Resources