Map SQL Query results into entities (C#) - c#

Is there a way to automap a query into a class in C# in order to strong type the query results? I don't want to access to query result with a DataTable, specifying manually the Column Name anymore.

There is couple of options:
EntityFramework - powerful and heavyweight. https://msdn.microsoft.com/en-us/library/aa937723(v=vs.113).aspx
Dapper - lightweight - mostly mapper https://www.codeproject.com/Articles/212274/A-Look-at-Dapper-NET
If you need only mapping of stored procedures, queries etc, Dapper is good way to go, as it's basically adding extension methods to connection object. It cannot create database etc as Entity Framework but it all really depends on needs.

My favourite question. Use QueryFirst. Write your SQL in the SQL editor window, syntax validated as you type, then QueryFirst will generate the C# wrapper to execute it, with strongly typed inputs and outputs. And there are numerous other benefits :-) SqlServer, MySql and Postgres support built in. Others easy to add. Disclaimer : I wrote QueryFirst.

You should take a look at AutoMapper. It's an easy and user-friendly way to map a DataTable to a List<object> of your specification.
You can find an article which talks about it (including sample code) here.
If you want to automize the process, you can use dynamic objects which don't require you to create specific classes for every DataTable that you're using.Hope this helped!

There is a helpful library on LINQ to DB
"LINQ to DB is the fastest LINQ database access library offering a simple, light, fast, and type-safe layer between your POCO objects and your database."
https://github.com/linq2db/linq2db

Related

How to query data from synonyms using odp.net managed driver in c#?

I have a connexion to a service in which I only have access to synonyms (i.e., I cannot create any view, procedure, ...) and I intent to query data from them. I'm using ODP.NET managed driver to do so but until now I found nothing to achieve that. I'm left with hard-coding all the queries but before doing that I wanted to ask if it's possible somehow to map c# classes to oracle synonyms if that makes sense at all.
Thanks in advance!
Mapping c# classes to database entities is typically done with an object relational mapper like Entity Framework. Unfortunately, the Oracle provider for EF doesn't support synonyms (source).
Personally I would give a MicroORM like PetaPoco, NPoco or Massive a try.
All of those options give you the possibility to map query results to classes.

Code Generator for populating a POCO class of table 'OrderHeader' based on ADO.Net SqlReader

I have a table called 'OrderHeader' in a SQL Server 2008 R2 database.
While I have found tools to generate the POCO class for this table in an automated manner, I cannot find a tool that will also generate the code to populate this class using SqlDataReader. This can help me save a lot of my time since I am writing low level ADO.Net code in my current project that uses SqlDataRader to populate data classes.
My question is: Is there any such tool ?
There are several free libraries that do this sort of mapping from SQL query results to POCO as a part of their broader functionality. AutoMapper for instance can convert your SqlDataReader to an appropriate IList<T> without too much difficulty, as can NHibernate apparently.
Another option is to use a framework like LinqToSQL or the EntityFramework to encapsulate your data, then build your queries against those. There are any number of good reasons to use EF or L2S for this, including such (probably) useful things as lazy loading and such.
Or you could learn to use reflection and build your mappings at runtime. I've used Linq Expression objects to do this in the past, but it's a lot of work to get only a little gain. It's fun to learn though :P
I'd suggest reading this article for more on reflection. It even has a simple example of using reflection to map an IDataReader to any type. It's not a complete solution since it doesn't handle DBNulls or any difference between your POCO and the data returned from the server will throw some exceptions. Make sure you read the whole article, then go investigate anything that still isn't clear.
If you want to go deeper than that, you can use Linq Expressions to build mapping functions for your types, then compile those expressions to Func<IDataReader, T> objects. Much easier than using System.Reflection.Emit... although still not simple.

What's Different Between LINQ and Entity Framework?

I know the benefit of the LINQ and I know use of it in .Net Application. I fill same thing there are providing as a Entity Framework.
So What's Major Difference between LINQ and Entity Framework?
LINQ could be applied to any data source: in-memory objects, XML, SQL, ...
Entity Framework could use LINQ to perform queries against a relational database.
LINQ to SQL is the predecessor of Entity Framework and is obsolete now.
Comparing EF and LINQ is incorrect. Both are different things and they often work together to give better developer experience (and productivity benefit).
LINQ is querying syntax/model that can be applied to any data source. EF provides one such data source.
They are somewhat similar, and can be used in a very similar way, code-wise, but they have some important differences. Note that "LINQ" is not the same thing as "LINQ to SQL"; the EF also uses LINQ. Some notable differences are:
LINQ to SQL is largely SQL Server only, not so much by design as by implementation. The EF is designed to support, and does support, multiple DBs, if you have a compatible ADO.NET provider.
Out of the box, LINQ to SQL has a very poor story for DB metadata changes. You have to regenerate parts of your model from scratch, and you lose customizations.
The EF supports model features like many-to-many relationships and inheritance. LINQ to SQL does not directly support these.
In .NET 3.5, LINQ to SQL had much better support for SQL-Server-specific functionality than the EF. This is mostly not true in .NET 4; they're fairly similar in that respect.
The EF lets you choose Model First, DB First, or Code First modeling. LINQ to SQL, out of the box, really only supports DB First.
SOURCE : Here
I totally agree with VinayC. You cannot really compare.
With Entity Framework, you will be able to have a whole representation of your database in your program. It will help you create classes corresponding to the database elements, connected together like they are in the database. You can after interact with elements of theses classes directly, and like this impact the database. You will have some representation of these classes diagram in visual studio. It's basically often simpler than working directly with the database elements, even if setting it up requires some effort.
The use of Linq is to perform queries on the data sources.

How can I easily store my C# data structure(XML serialiazable) into a database?

I have a C# data structure which consists of classes and collections which have references to each other. Currently I am using Serialization to store the structure in XML, which works as a handy way to save/load the structure into my application.
If I want to be able to save/load the structure into a database, is there a simple way? Should I use LINQ?
Just to be 100% clear LINQ has nothing to do with storing data in a database. LINQ is a language query for c# with syntax that resembles SQL.
So in order to answer your question you could look at the Entity Framework (I'd recommend this if you are using .NET 4.0) or LINQ to SQL
It currently depends on your needs, and the db engine you are using:
If you need to perform queries against the XML contents you can use a XML field (mssql and oracle do support them).
If you only need to store/retrieve it, just store it in a long string field (NText in sqlserver. NCLob in Oracle).
Have you tried NHibernate?
EDIT: I don't know if this would be ok for you, but if you can define DB tables to hold your data structures, you could have code auto-generated using LINQ to SQL. Check ScottGu's tutorial on LINQ to SQL. If your data structures are not changing too often this could be a good way to go.

Linq to SQL for a new project

I am about to start a new project and am deciding what data access technology I will be using... I really like LINQ to SQL for a variety of reasons but should I start the new project using the Entity Framework instead??
I have this perception that the Entity Framework is more bloated and needlessly complicated, thus accounting for part of the reason I was thinking about going with LINQ to SQL... but as I said this may only be perception on my side as I haven't used the Entity Framework all that much.
So which would people recommend I use for starting a new project today (note this app will be around for years to come)?
Cheers
Anthony
EDIT:
We are SQL Server shop so we don't need database vendor independent.
Also is the generally agreed best way to abstract data access atm by using the Repository pattern which works with my domain objects?
LINQ to SQL is about rapid development and simplicity. If your data model is complex, or might become so, you will be better off using a more robust framework.
That said, more important than your data access tool is how well you abstract it from the rest of your code. Done right, you should be able to start with LINQ to SQL and switch when you outgrow it (or when EF 2 4 comes out).
Note that EF 1 is far from complete. It lacks all kinds of features you do find in LINQ to SQL, one of the more important ones being actual foreign key properties (can you imagine these don't exist in EF 1?)
Also, EF 4 will pretty much have all features of LINQ TO SQL, and both will generate relatively comparable (code wise) external API, so unless you're coding to very LINQ to SQL specific API's, it should be relatively easy to migrate to EF4 later on, 'simply' by replacing the LINQ to SQL .dbml with EF4's equivalent.
Linq to SQL works best in an active record / one table per class paradigm. If you need to span your class across several tables, or support complex inheritence then it may not be the best choice. Also, Linq to SQL doesn't natively support many-to-many relationships (there are workarounds).
If neither of those sound like they'd affect you, then Linq 2 SQL may be a good choice. It's a great lightweight data access strategy.
Linq to SQL can be used to implement the repository pattern very well given the above constraints. Google will turn up several viable Linq repository examples.
Have you taken a look at Subsonic - now in version 3 it is basically a linq to sql DAL that makes it possible to have full linq to sql of your entire database in under 5 mins. And it runs off T4 templates, so if you want to add to the templates it is REALLY EASY
http://www.subsonicproject.com/
I wrote up a pretty lengthy blog post on choosing a .NET ORM:
.NET and ORM - Decisions, decisions
Basically, NHibernate is your best bet. If you insist on something with simplicity like LinqToSql, consider SubSonic. I would not recommend either of the Microsoft options: LinqToSql or EntityFramework.
Deciding whether to use the repository pattern or not is situational depending on your requirements.
Check out: http://www.icemanind.com/Layergen.aspx

Categories

Resources