create entities for a dynamically created database in SQL Server - c#

I have an application where I create database's dynamically in a SQL Server using Server Management Objects through my application.
I want to use the Entity Framework to access this database when it has been created, is this possible? As I can not generate Entity classes from a database in VS. I do have the structure of the database of course.
So is it possible to create the Entity classes manually and is that a do-able task?

Yes, it's completely possible. You can even manipulate the generated code if you want.
What you might want to take a look is the EDMX XML specification.
In that file you specify the underlying database, views, functions, procedures and the like, as well as the desired objects. Take a look at MSDN in order to have more information.

Paulo is right for EF 1 (+1). For EF 4, I'd suggest using code-only modeling instead.

Related

Is there any way I can automatically generate BLL classes for a particular database table in c# .NET?

I have been writing BLLs for whatever new tables I create in the database and use them in the Data access layer. I was wondering if someone knows if there is an inbuilt option using .NET for generating BLL classes for a table in sql server database.
It depends on what you want on your objects or the behavior you want to give to them.
You already have Entity Framework as a possibility, that already does something very similar to what you describe.
There is also LLBL Gen Pro (not free, but amazing) that probably does everything you want.
You can also make your own code generator tool combining a template engine (like T4), with queries against your master database, perhaps using MicroORM to simplify DB access.

C# Is there an easier way to create a database, empty tables, tables with data in them by default, stored procs and views?

Before I posted this question, I did some Googling first on how a database was created through C# and mostly it points to either SMO or SQL query files and it was the time of SQL Server 2005 and 2008.
So at this day in age, is there an easier way to create a database with empty tables, tables with data in them by default, stored procedures and views?
I need a suggestion.
I think the answer is probably Entity Framework. You can do 'code first' and use database migrations, allowing you to write your C# code and use that to generate a lot of the database for you.
Ultimately though, 'easier' is subjective. I personally find EF great for the 'normal' stuff, but at the end of the day, if you need a stored procedure to do some custom logic; you need to write the custom logic, in some fashion.
Maybe have a look and see if you think it fits your needs.
https://www.asp.net/mvc/overview/getting-started/getting-started-with-ef-using-mvc/creating-an-entity-framework-data-model-for-an-asp-net-mvc-application
Looked at the database projects in studio 2013. You create a database as a series of scripts using a familiar GUI. However, changes are published - this process creates a unique change script targeting the connection you define. For new databases the whole thing gets created, but publish against a partial or out dated version and the script created in a change script to bring it up to date.
You can even writ unit tests against your database using specialist tools, although I do find them lacking a bit.
More on msdn - here
Depends. right out of gates. Sp and views. Best shot is directly from database through a workbench. I can then capture definitions and store in a file to be replayed through c#
As for tables there are many orms that can generate tables via c#. Look at entity frameworks. Code first examples
I have generated tables using EF Works fine. I then went into database and created views and sps.
The trick is to migrate new views and sps into your EF model U can google entity Frameworks code first ... Adding views and SPs.
Worst case is u create database all through database workbench. Create a script that an be played to recreate eveything. By running. Then use EF DATABASE first approach
In either case u end up with a good set of autogenerated code to manage CRUD and object management and an abstracted data model

NHibernate to dynamically create/alter/delete tables

I know NHibernate is an ORM and it isn't normally used to create tables but I also know that NHibernate is able to create an entire database given some mappings.
I would like to know if there is an obscured API that I could use to dynamically create/alter/delete tables. I could do it with ADO.Net but I would like to abstract the code for creating tables for different databases (MS SQL, MySQL, etc.)
Precision 1: The problem with CreateSQLQuery is that I would have to rewrite the method for creating a table for different SQL servers (MS SQL, MySQl, etc.) It has no advantages over ADO.Net. When NHibernate generates the database from mappings it generates for any SQL servers... that is what I'm looking for. What is the code that is executed when NHibernate generates a database from mappings... is this code available/public?
Yes you can :)
You create dynamically a Type corresponding to the class to be mapped. And then generate a mapping.
The important classes to look in NH source code are in the Nhibernate.Mapping namespace : PersistentClass, RootClass.
Here is a sample :
https://nhibernate.info/blog/2008/11/16/mapping-source-how-map-a-class-without-use-nothing.html
I have used this "API" to generate dynamically Tables.
There isn't a specific API to dynamically create/alter/delete tables. Depending on what you need to do and when you want these actions to happen you have the following options:
Use the tag in the xml mapping files to perform whatever action you want on the database just after your schema is generated
Use named queries and in the mapping files to create SQL statements to run from your code. (I have never tried these with create/alter/delete table commands but its worth to try).
Use the Session.CreateSQLQuery() method to execute a native SQL command. (Again as the previous option I have never tried it with create/alter/delete table commands but I believe its worth to try).
You could use the schema object.
You need to configure NHibernate and using the schema object call create. the two boolean values will either drop the database and recreate it or just output it to the console.
VB.Net
Public Sub CreateDatabaseSchemaFromMappingFiles()
Dim cfg As New NHibernate.Cfg.Configuration()
cfg.Configure()
Dim schema As New NHibernate.Tool.hbm2ddl.SchemaExport(cfg)
schema.Create(True, False)
End Sub

Automatically create C# wrapper classes around stored procedures

I've inherited a rather large application that really could use some cleanup. There is data access code littered throughout the application. In code behinds, some in business logic classes, some inline in in classic asp pages.
What I'd like to do is refactor this code, removing all the data access code into a few DAL classes.
All the data access is done through stored procedures (Microsoft SQL 2000). There are 300-400 of them.
It seems like there should be an automated way to analyse the store procedures, and automatically generate c# methods for each of them, mapping the Method parameters to the stored procedure parameters, with a method returning a datatable.
I don't have any experience with ORM products, and I'm not sure if what I'm looking for is a full blown ORM, or just a 3rd party utility that will help generate simple wrappers around the sp calls.
If you have access to .NET Framework 3.5 and Linq to SQL, you can do it very easily, check this video:
LINQ to SQL: Using Stored Procedures
Using existing stored procedures and
functions is easy with LINQ. We simply
drag the stored procedures onto the
O/R mapping surface and call them from
the generated Data Context object.
I recommend you get a hold of Code Smith. The product includes a template for ORM and fully supports generating classes from DB Schemas (and I think Procs). You can then Code Gen all the objects you need.
Another option would be to use LINQ to SQL.
My approach would be to think higher level first- create your data access classes and methods the best way you can to fit your needs for your existing or new code base. Then, use the existing procedure calls for your new objects.
I do not think you should consider any form of mass automation for this task.
dragging and dropping the stored procedures onto a dataset design surface (in .net 2.0 and higher) generates a wrapping function
but if you have a lot of them to do, you might be better off using or writing a simple code generator
two options for this:
generate the wrapping code yourself as C# classes/methods
generate a dataset.xsd file then open it in visual studio and let the designer generate the classes/methods for you
the latter can be maintained via the dataset design surface, but may be tricky to get generated right (the first time)
Similar to Robert's suggestion, we've written our own version of Code Smith.
Our "Code Generator" has two parts: SQL & Classes.
SQL:
Will generate the Update, Select & Delete stored procs.
C#:
Will generate the classes and save the file as a .cs
We call:
sp_MShelpcolumns 'tablename' to get a list of fields and data types and then do a replace.
Its not a perfect solution, but is very effective to getting the first 80% completed
Not for sure, but seems like this is exactly what you were asking for.
http://www.codeproject.com/KB/database/SPGenerator.aspx

How can I leverage an ORM for a database whose schema is unknown until runtime?

I am trying to leverage ORM given the following requirements:
1) Using .NET Framework (latest Framework is okay)
2) Must be able to use Sybase, Oracle, MSSQL interchangeably
3) The schema is mostly static, BUT there are dynamic parts.
I am somewhat familiar with SubSonic and NHibernate, but not deeply.
I get the nagging feeling that the ORM can do what I want, but I don't know how to leverage it at the moment.
SubSonic probably isn't optimal, since it doesn't currently support Sybase, and writing my own provider for it is beyond my resources and ability right now.
For #3 (above), there are a couple of metadata tables, which describe tables which the vendors can "staple on" to the existing database.
Let's call these MetaTables, and MetaFields.
There is a base static schema, which the ORM (NHibernate ATM) handles nicely.
However, a vendor can add a table to the database (physically) as long as they also add the data to the metadata tables to describe their structure.
What I'd really like is for me to be able to somehow "feed" the ORM with that metadata (in a way that it understands) and have it at that point allow me to manipulate the data.
My primary goal is to reduce the amount of generic SQL statement building I have to do on these dynamic tables.
I'd also like to avoid having to worry about the differences in SQL being sent to Sybase,Oracle, or MSSQL.
My primary problem is that I don't have a way to let ORM know about the dynamic tables until runtime, when I'll have access to the metadata
Edit: An example of the usage might be like the one outlined here:
IDataReader rdr=new Query("DynamicTable1").WHERE("ArbitraryId",2).ExecuteReader();
(However, it doesn't look like SubSonic will work, as there is no Sybase provider (see above)
Acording to this blog you can in fact use NHibernate with dynamic mapping. It takes a bit of tweaking though...
We did some of the using NHibernate, however we stopped the project since it didn't provide us with the ROI we wanted. We ended up writing our own ORM/SQL layer which worked very well (worked since I no longer work there, I'm guessing it still works).
Our system used a open source project to generate the SQL (don't remember the name any more) and we built all our queries in our own Xml based language (Query Markup Language - QML). We could then build an xmlDocument with selects, wheres, groups etc. and then send that to the SqlEngine that would turn it into a Sql statement and execute it. We discusse, but never implemented, a cache in all of this. That would've allowed us to cache the Qmls for frequently used queries.
I am a little confused as to how the orm would be used then at runtime? If the ORM would dynamically build something at runtime, how does the runtime code know what the orm did dynamically?
"have it at that point allow me to manipulate the data" - What is manipulating the data?
I may be missing something here and i aplogize if thats the case. (I only have really used bottom up approach with ORM)
IDataReader doesn't map anything to an object you know. So your example should be written using classic query builder.
Have you looked into using the ADO.NET Entity Framework?
MSDN: LINQ to Entities
It allows you to map database tables to an object model in such a manner that you can code without thinking about which database vendor is being used, and without worrying about minor variations made by a DBA to the actual tables. The mapping is kept in configuration files that can be modified when the db tables are modified without requiring a recompile.
Also, using LINQ to Entities, you can build queries in an OO manner, so you aren't writing actual SQL query strings.

Categories