Generating db schema from c# class - c#

Is there any other method than nHibernate by wich we can generate db schema from class definition? My classes arn't that complex etc (few one-to-many relations). However I would like to just be able to save my objects in db and recreate schema if needed.
I am stuck with .NET 2.0. I am not that particular about performance for this project, I am just lazy to create tables and write save/load code and deel with nHibernate xml.
Thanks

.NET classes are not compatible with a relational data model. That's why ORMs such as NHibernate exist. Without a mapping which describes the conversion of the model to relational tables you cannot create a DB schema. You could take a look at FluentNhibernate automapping feature. If you stick to the conventions it can create the database schema from .NET classes.

NHibernate can do this. The relevant classes -- SchemaExport and SchemaUpdate -- are in the NHibernate.Tool.hbm2ddl namespace. Here's one example.

Yes, ther are other ways. THis is called "programming" - you may have heard of that. Basically, it is possible to write your own database generator. Been there, done that, long before nhibernate had that functionality (or, actually, even existed).
Sit down, write your own database generator.

Related

entity framework clarification about model objects and their methods

I had a conceptual question about EF.
I am pretty new to the idea of an ORM in general, so I wanted to get some clarification on somethings:
I have an existing database, and I want to convert the data I am pulling from that data into objects that my application can interact with as objects, rather than just data.
An ORM will accomplish that, correct?
In EF can I create methods specific to my objects? For instance, can I make it so my application can call something like employee.ViewDetails() Where employee is an object?
If so, is there a simple tutorial you could recommend?
Is EF portable between applications? Meaning, is it easy to build an EF structure and then port it to multiple applications?
I can just do that by referencing it from different solutions, no?
Thanks for all the help
Before Answering your Question let me give you short brief about Entity Framework
Using the Entity Framework to write data-oriented applications provides the following benefits:
Reduced development time: the framework provides the core data access capabilities so developers can concentrate on application logic.
Developers can work in terms of a more application-centric object model, including types with inheritance, complex members, and relationships. In .NET Framework 4, the Entity Framework also supports Persistence Ignorance through Plain Old CLR Objects (POCO) entities.
Applications are freed from hard-coded dependencies on a particular data engine or storage schema by supporting a conceptual model that is independent of the physical/storage model.
Mappings between the object model and the storage-specific schema can change without changing the application code.
Language-Integrated Query support (called LINQ to Entities) provides IntelliSense and compile-time syntax validation for writing queries against a conceptual model.
Going Back to your first Question
Yes
Entity framework is useful in three scenarios.
1- First, if you already have existing database or you want to design your database ahead of other parts of the application. (Which is your current case)
2- Second, you want to focus on your domain classes and then create the database from your domain classes.
3- Third, you want to design your database schema on the visual designer and then create the database and classes.
2) in EF can I create methods specific to my objects? For instance, can I make it so my application can call something like employee.ViewDetails() where an employee is an object? If so, is there a simple tutorial you could recommend?
Yes Sure Take a look on this:
- https://msdn.microsoft.com/en-us/library/dd456847.aspx
- http://www.asp.net/mvc/overview/older-versions-1/models-data/creating-model-classes-with-the-entity-framework-cs
3) Is EF portable between applications? Meaning, is it easy to build an EF structure and then port it to multiple applications? I can just do that by referencing it from different solutions?
you might need to Implementing the Repository Patterns
Have a look at this Amazing tutorial
http://blog.gauffin.org/2013/01/repository-pattern-done-right/
http://rycole.com/2014/01/25/entity-framework-repository-pattern.html
Hope this helps!
Wish you the best :)
Blubberbo,
There are various ways to work with EF, they are Code First, Model First and Database first.
More information can be found in the below SO post.
Code-first vs Model/Database-first
1) You can use LINQ to SQL or LINQ Objects in context with an ORM like EF to interact with Objects.
2) If you would like methods specific to specific types, then you might want to take a look at writing extension methods for specific types.
More information here
https://msdn.microsoft.com/en-us/library/bb311042.aspx
3) To make it portable, you might want to build abstractions around it, like for example you might want to write repository classes to separate the DB layer that uses EF and the layer that calls it(a.k.a the repository layer).
More info can be found here
http://www.asp.net/mvc/overview/older-versions/getting-started-with-ef-5-using-mvc-4/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application
Hope that helps,
Praveen Raju

Is it possible to use Entity Framework and keep object relations in the code and out of the database

I'm having a hard time just defining my situation so please be patient. Either I have a situation that no one blogs about, or I've created a problem in my mind by lack of understanding the concepts.
I have a database which is something of a mess and the DB owner wants to keep it that way. By mess I mean it is not normalized and no relationships defined although they do exist...
I want to use EF, and I want to optimize my code by reducing database calls.
As a simplified example I have two tables with no relationships set like so:
Table: Human
HumanId, HumanName, FavoriteFoodId, LeastFavoriteFoodId, LastFoodEatenId
Table: Food
FoodId, FoodName, FoodProperty1, FoodProperty2
I want to write a single EF database call that will return a human and a full object for each related food item.
First, is it possible to do this?
Second, how?
Boring background information: A super sql developer has written a query that returns 21 tables in 20 milliseconds which contain a total of 1401 columns. This is being turned into an xml document for our front end developer to bind to. I want to change our technique to use objects and thus reduce the amount of hand coding and mapping from fields to xml (not to mention the handling of nulls vs empty strings etc) and create a type safe compile time environment. Unfortunately we are not allowed to change the database or add relationships...
If I understand you correct, it's better for you to use Entity Framework Code First Approach:
You can define your objects (entities) Human and Food
Make relations between them in code even if they don't have foreign keys in DB
Query them usinq linq-to-sql
And yes, you can select all related information in one call.
You can define the relationships in the code with Entity Framework using Fluent API. In your case you might be able to define your entities manually, or use a tool to reverse engineer your EF model from an existing database. There is some support for this built in to Visual Studio, and there are VS extensions like EF Power Tools that offer this capability.
As for making a single call to the database with EF, you would probably need to create a stored procedure or a view that returns all of the information you need. Using the standard setup with lazy-loading enabled, EF will make calls to the database and populate the data as needed.

Entity Framework destriong my classes

Why when I saving the EDMX file in VS2012, hi always change the attributes of the component classes?
I use a marker there [NotMapped] with System.ComponentModel.DataAnnotations.Schema and it is always the same clause and using are removed.
EF does not support Agility methodologies?
1) I want to just make simple calculations on the data and display them in the attributes. For example, the document number is the number and prefix.
2) the model-first and code-first for me is not enough. I create an application based on data from the ERP and I have to add Me own document type. Half of the data is in the database and I can not duplicate it. The other half is my new tables. At the same time I do not know yet where I will use the data and I am not sure what the relationship between them I used. (I can not create a relationship right away in the diagram on the 500 tables). The client does not know yet what the data which depends. Typical thing to Agile methodologies.
Learn and use the code-first approach. It will give you full control over your POCOs (plain old class objects). The model-first approach requires that you use the EDMX modeler to make your changes which does not allow you to do much customization underneath.
Entity Framework Tutorial website is a good resource to get started as is the official Entity Framework website.

EntityFramework (ORM) object names and domain model names - how to avoid duplicates?

Let's say I have a project where I use Entity Framework, but I want to use my own classes instead of the EF classes.
Reasons for using my own classes:
Easy to add properties in code
Easy to derive and inherit
Less binding to the database
Now, my database has table names like User and Conference.
However, In my domain project, I also call my files User.cs and Conference.cs.
That means I suddenly have two objects with the same naming, which is usually very annoying to work with, because you have to use namespaces all the time to know the difference.
My question is how to solve this problem?
My ideas:
Prefix all database tables with 'db'. I usually do this, but in this case, I cannot change the database
Prefix or postfix all C# classes with "Poco" or something similar
I just don't like any of my ideas.
How do you usually do this?
It's difficult to tell without more background but it sounds like you are using the Entity Framework designer to generate EF classes. This is known as the "Model First" workflow. Have you considered using the Code First / Code Only workflow? When doing code first you can have POCO classes that have no knowledge of the database, EF, or data annotations. The mapping between the database and your POCOs can be done externally in the the DBContext or in EntityTypeConfiguration classes.
You should be able to achieve your goal of decoupling from EF with just one set of objects via code first.
To extend the above answer, the database table name User (or Users as many DB designers prefer) is the identifier for the persistence store for the object User that's defined in your code file User.cs. None of these identifiers share the same space, so there should be no confusion. Indeed, they are named similarly to create a loose coupling across spaces (data store, code, development environment) so you can maintain sanity and others can read your code.

Strongly Typed DataSet with a set of TableAdapters per database provider?

I want a strongly-typed DataSet along with designer TableAdapters, but Visual Studio's DataSet designer generates provider-specific (e.g. SQL Server vs. MySql) code and I don't want to commit to just one provider. An ORM would help, but:
Entity Framework is 3.5 only and doesn't play nice with DataSets, and
NHibernate doesn't support SQLite.
Here's what I've come up with:
"DataSets.Masters" contains a completely designed DataSet bound to some particular provider (e.g. SqlClient), including:
a CustomTableAdapter component, subclassed by each designer TableAdapter,
an ITableAdapterManager interface, implemented by designer's TableAdapterManager for hierarchical updates.
Everything except the DataSets.MyDataSetTableAdapters namespace is copied into the "DataSets" project, where all the TableAdapter code (along with xs:annotation) is removed.
The DataSets.MyDataSetTableAdapters namespace, along with MyDataSet.xsd etc., is copied and customized into each of "DataSets.SqlClient", "DataSets.SQLite", etc. each of which references the "DataSets" assembly.
Now I just have to choose the right assembly to load my ITableAdapterManager implementation from, based on any given connection string. When the table schema changes, I modify the Masters assembly, copy code to the production assemblies, and run a few tests.
So my question: am I making this too difficult? DataSets are so standard, and the need to support multiple database engines via the data access layer is so common, is there a method that doesn't involve copy, paste, and search & replace? What do you do?
It might be easier to simply ignore the autogenerated TableAdapter commands and use the ADO.Net data access factory objects when it's time for your CRUD operations. That way you can use DbProviderFactory.CreateCommandBuilder to correctly format the parameters in the CRUD operations. Note that this assumes that you aren't doing any tricky property mapping and your schema will remain consistent across data providers.
An aditional option if you use this technique is to create a class that you can enter as the BaseClass property on your TableAdapters. Add an "init"-type method that overrides the connection and the insert, delete, select, and update commands with ones from the factory (based on the auto-generated select command—which should be compatible across most providers).
NHibernate does support SQLite http://www.hibernate.org/361.html.
I recommend using NHibernate combined with Fluent NHibernate. Fluent NHibernate is a library that allows you to use NHibernate without needing to deal with any xml yourself which in my opinion is NHibernate's greatest drawback.
Also Fluent NHibernate supports an auto persistence model that if your domain objects are close to your database schema you can automap your entire business domain without writing mapping code for every single object. The further your business objects differ from your database the more complex it becomes to use the automapping features of Fluent NHibernate and it's worth using static mapping.

Categories

Resources