Dynamic table name in entity framework linq - linq

I am currently using entity framework (.net 4) to read from a 3rd party database using LINQ statements. Unfortunately, at compile time i do not know from which table i will be reading - in fact, new tables can be added to this database after my application is compiled. The table name to read from will be passed as a string parameter to my method.
How should one approach this situation when the table name is not know at compile time? i cannot even add these tables to my data model since they might not yet exist. whilst i like the convenience of linq, i am after a simple approach.
thanks!

For the queries that can only be constructed at run-time and that will return types of different shapes, you're pretty much forced to craft and execute the SQL you want to run yourself. DataContext.ExecuteQuery(string query, params object[] parameters) is going to be your friend.
You probably would already do this, but I would recommend keeping this portion of code isolated to one section of the code, where you execute the query, and then put the results into an strongly typed object before exposing it to other area's of your application. Make sure you clean the table name too.

Related

Linq query will change often- how can I change it without recompiling app?

My application will be querying a database using Entity Framework. The problem is that the database table structure changes fairly often (a few times a year).
Back in the SQL days, we would store SQL queries in Resource files (.resx) and when any database changes occurred, we could just edit the one resource file and not have to edit any code in the app, recompile, etc.
Are there any good ways to do this with Linq-to-SQL?
Linq2SQL is innately code-based. If your schema is going to change, then the code will need to change.
The only way I can see around this, and still get some of the benefits of linq, is to write everything as Stored Procedures, which you can than add as method to the linq DataContext.
Then, as long as the Name, input parameters and output columns remain the same, you can change what the SP is doing on the database and the code can stay the same.

Mapping View to Entity using EF 5 Code First

I have developed a quite nice web-app using EF 5 and code first. But while running benchmarks I found that the performance was not as good as I wanted... looking further I kinda figured out that all the queries that EF generates are similar to Select * From and that is not best practise.
Reading this answer here Select Specific Columns from Database using EF Code First I understood that I could generate a view and map it to a entity. My question is how do I map a view to a entity or vice-versa using EF 5 code first?
The reason I'm asking this is: I have a very wide table on which I perform "preliminar search" search items by name and then go back for the rest of it on one case... in another I have a big table and most of the time I only use the Title and Description and not the LOB column... in all thouse cases Im getting something from the database Im not using...
So if I could indeed map a view to a entity or vice-versa I could save alot of bandwith between backbone and application tier...
It's not the same thing you're talking about - i.e. not an exact answer - but it's addressing performance, via what EF calls 'views'.
I'd suggest you try out the EF Power Tools - and 'Generate Views'.
By running that - the 'views' file is added to the project - which is a .cs one - and that enhances the core EF performance (this is an EF feature, not the code-first - but with power-tools we can now use it with code-first as well).
It doesn't add the 'Db views' - but as far as I can tell - it works by pre-analyzing and code-generating the SQL templates.
"Before the Entity Framework can execute a query against a conceptual
model or save changes to the data source, it must generate a set of
local query views to access the database. The views are part of the
metadata which is cached per application domain. If you create
multiple object context instances in the same application domain, they
will reuse views from the cached metadata rather than regenerating
them. Because view generation is a significant part of the overall
cost of executing a single query, the Entity Framework enables you to
pre-generate these views and include them in the compiled project. For
more information, see Performance Considerations (Entity Framework)."
http://msdn.microsoft.com/en-us/library/bb896240.aspx
I could 'feel' a boost in performance.
Notes:
There are couple issues with it - and you might get some exceptions running it the first time:
Make sure your class is the only context in the file (it takes the first one),
I had to move the project out of a 'solution dir' (that is a trick I learned from power-shell console - which required the same)
Also, any other attempts to manually 'tweak' the Db with the 'real' views - would be futile I think, as it isn't closely integrated w/ the ORM (you need more then one - and matching calls etc.).
the way I achieve that is not very clean but:
I create a type
declare a dbset for the type
drop the table in the db if necessary
create a view named as the dropped table with the same field (type and name).
Of course all that is encapsulated in the seed method.
Not clean but running. I think some trouble is to come if you want to "migrate" the structure of the view. But this way all his nearly as if you get an entity. Of course insertion and update may be touchy, but this is not my purpose.
if you respect the naming convention even the loading strategies are available.

Moving from SQL-query-based approach to Linq

I'm not so good at both Linq and SQL. But I have worked more with SQL and less with LINQ. I've gone through many articles which favors LINQ. I don't want to go the SQL way (i.e. writing stored procedures and operating data etc.)
I want to start with LINQ for every operation related with data. Here are the reasons why I want to do this:
I want to have complete control of my database via application and not by writing stored procs (as I'm not so good at writing store procedure)
I want to create my project as an easy maintainability view
Want faster development
For that, I know that:
I need to add a dbml file, drag and drop tables into that
Use dbContext class, and so on
But I want to know, is there a way:
I can avoid creating dbml file and still be able to access the database?
Do I need to use Linq to Entities for the same?
Will it be a good way to avoid using dbml file? Since for every database changes I need to drop and drop tables every time
Also I've come across many posts where linqToSql is considered deprecated and not a .net future?
I have so many doubts, but I think that's obvious when starting with a new technology?
I found this useful article which is good for beginners:
[http://weblogs.asp.net/scottgu/archive/2010/08/03/using-ef-code-first-with-an-existing-database.aspx][1]
after doing some more research I came to conclusion that:
1)i can avoid creating dbml file and still be able to access database??
ANS Yes but instead of dbml now edmx files will be created.
2)Do I need to use Linq to Entities for the same?
ANS Yes you can go with linq to entities.
3)Will it be good way avoid using dbml file? since for every database changes I need to drop and drop tables every time
ANS it is not required to drop and create again the tables. their are options where you can update selected part of your database and you are not avoiding dbmls. it will created edmx file and that will almost similar to dbmls in many ways.
4) Also I've come across many posts where linqToSql is considered deprecated and not a .net future?
ANS yes in future development it will be depreciated. it supports only sql server as backend.
I hope I'm right. Please do tell me in case any other suggestions.
LINQ is a way to query and project collection of data. For example, you can use LINQ to query and shape data from a database or from an array. LINQ by it self has nothing to with the under lying database.
You use an ORM (Object Relational Mapper) technology to project data stored in tables of a database as collections of objects. Once you have the collection of objects, you can use LINQ to query them.
Now, you have many ORM technologies to select from, such as Entity Framework, NHibernate, Linq2Sql. If you don’t like to maintain a dbml file, have a look at code first approach offered by Entity Framework.
Then there are things called LINQ data providers. They would take a LINQ query, transform it to a SQL targeting a particular database, execute the query and get the results back as a set of objects. Many of the ORMs above has built in LINQ data providers as a part of them and would work behind the scene in fetching the data.
I would advise you to look up on some patterns such Repository and Unit of work for your data layer. When used correctly, these patterns will isolate your data access code from your applications upper layers. This will help you to change your data access technology is it becomes obsolete, without affecting the rest of the application.
LINQ is an awesome technology and you should definitely try it
I have composed the above answer based on my own experience and I am sure there are many SO users with better understanding of the above technologies than myself who may wish to add their own opinion
Good luck

Code first approach versus database first approach

I am working on an asp.net MVC 3 web application and I am using database first, but after I have mapped the DB tables into entity classes using entity framework, I am interacting with these tables as I will be interacting on the code first approach by dealing with Database tables as classes an objects.
So after mapping the tables into entity classes I find that the code first approach and DB first are very similar but except of start writing the entities classes from scratch (as in code first) I have created the entity classes from existing database tables - which is easier and more convenient in my case.
So are there specific cases on which i will not be able to do some functionalities unless i am using one approach over the other which till now i cannot find any?
Having dealt with many many headaches using db-1st EDMX pre EF 4.1, I am partial to code-first. But I'm not going to evangelize it.
In addition to the direct sproc mapping & function import features mentioned in Pawel's answer & comment, you won't be able to change the namespaces or any other code in the generated files when you use db-first. Afaik all of the files are nested under the .tt file. If there is a way to move them into logical folders & namespaces in your project, then I'm not aware of it.
Also if you ever want to separate your DbContext into a separate project from your entities, I recall this was possible pre-EF 4.1. But it was more cumbersome, because you had to run custom tool on both .tt files after each db change. With code-first this is pretty straightforward because you're dealing with pure OOP.
I think that the biggest limitation of CodeFirst (as compared to ModelFirst/DatabaseFirst approaches) is that you cannot map your CUD operations to stored procedures. If you are not planning to do that then you should be good to go.
To be more specific - You can invoke stored procedures using SqlQuery method on DbSet which will cause the returned entities to be tracked or more general SqlQuery and ExecuteSqlCommand on Database class (for Database.SqlQuery the returned objects do not have to be entities and there is no tracking for these objects). That's about it. You cannot map Create/Update/Delete operations to stored procedures. FunctionImports are not supported as well
EDIT
It's possible to map CUD operations to stored procedures in EF6 now

NHibernate vs LINQ to SQL

As someone who hasn't used either technology on real-world projects I wonder if anyone knows how these two complement each other and how much their functionalities overlap?
LINQ to SQL forces you to use the table-per-class pattern. The benefits of using this pattern are that it's quick and easy to implement and it takes very little effort to get your domain running based on an existing database structure. For simple applications, this is perfectly acceptable (and oftentimes even preferable), but for more complex applications devs will often suggest using a domain driven design pattern instead (which is what NHibernate facilitates).
The problem with the table-per-class pattern is that your database structure has a direct influence over your domain design. For instance, let's say you have a Customers table with the following columns to hold a customer's primary address information:
StreetAddress
City
State
Zip
Now, let's say you want to add columns for the customer's mailing address as well so you add in the following columns to the Customers table:
MailingStreetAddress
MailingCity
MailingState
MailingZip
Using LINQ to SQL, the Customer object in your domain would now have properties for each of these eight columns. But if you were following a domain driven design pattern, you would probably have created an Address class and had your Customer class hold two Address properties, one for the mailing address and one for their current address.
That's a simple example, but it demonstrates how the table-per-class pattern can lead to a somewhat smelly domain. In the end, it's up to you. Again, for simple apps that just need basic CRUD (create, read, update, delete) functionality, LINQ to SQL is ideal because of simplicity. But personally I like using NHibernate because it facilitates a cleaner domain.
Edit: #lomaxx - Yes, the example I used was simplistic and could have been optimized to work well with LINQ to SQL. I wanted to keep it as basic as possible to drive home the point. The point remains though that there are several scenarios where having your database structure determine your domain structure would be a bad idea, or at least lead to suboptimal OO design.
Two points that have been missed so far:
LINQ to SQL does not work with Oracle
or any database apart from SqlServer. However 3rd parties do offer better support for Oracle, e.g. devArt's dotConnect, DbLinq, Mindscape's LightSpeed and ALinq. (I do not have any personal experience with these)
Linq to NHibernate lets you used
Linq with a Nhiberate, so it may
remove a reason not to use.
Also the new fluent interface to Nhibernate seems to make it less painful to configure Nhibernate’s mapping. (Removing one of the pain points of Nhibernate)
Update
Linq to Nhiberate is better in Nhiberate v3 that is now in alpha. Looks like Nhiberate v3 may ship towards the end of this year.
The Entity Frame Work as of .net 4 is also starting to look like a real option.
#Kevin: I think the problem with the example you are presenting is that you are using a poor database design. I would have thought you'd create a customer table and an address table and normalized the tables. If you do that you can definately use Linq To SQL for the scenario you're suggesting. Scott Guthrie has a great series of posts on using Linq To SQL which I would strongly suggest you check out.
I don't think you could say Linq and NHibernate complement each other as that would imply that they could be used together, and whilst this is possible, you're much better off choosing one and sticking to it.
NHibernate allows you to map your database tables to your domain objects in a highly flexible way. It also allows you to use HBL to query the database.
Linq to SQL also allows you to map your domain objects to the database however it use the Linq query syntax to query the database
The main difference here is that the Linq query syntax is checked at compile time by the compiler to ensure your queries are valid.
Some things to be aware of with linq is that it's only available in .net 3.x and is only supported in VS2008. NHibernate is available in 2.0 and 3.x as well as VS2005.
Some things to be aware of with NHibernate is that it does not generate your domain objects, nor does it generate the mapping files. You need to do this manually. Linq can
do this automatically for you.
Fluent NHibernate can generate your mapping files based on simple conventions. No XML-writing and strongly typed.
I've recently worked on a project, where we needed to change from Linq To SQL to NHibernate for performance reasons. Especially L2S's way of materializing the objects seems slower than NHibernate's ditto and the change management is quite slow too. And it can be hard to turn the change management off for specific scenarios where it is not needed.
If you are going to use your entities disconnected from the DataContext - in WCF scenarios for example - you're may have a lot of trouble connecting them to the DataContext again for updating the changes. I have had no problems with that with NHibernate.
The thing I will miss from L2S is mostly the code generation that keeps relations up-to-date on both ends of the entities. But I guess there are some tools for NHibernate to do that out there too...
Can you clarify what you mean by "LINQ"?
LINQ isn't an data access technology, it's just a language feature which supports querying as a native construct. It can query any object model which supports specific interfaces (e.g. IQueryable).
Many people refer to LINQ To SQL as LINQ, but that's not at all correct. Microsoft has just released LINQ To Entities with .NET 3.5 SP1. Additionally, NHibernate has a LINQ interface, so you could use LINQ and NHibernate to get at your data.
By LINQ, I'm assuming you mean LINQ to SQL because LINQ, by itself, has no database "goings on" associated with it. It's just an query language that has a boat-load of syntac sugar to make it look SQL-ish.
In the very basic of basic examples, NHibernate and LINQ to SQL seem to both be solving the same problem. Once you get pass that you soon realize that NHibernate has support for a lot of features that allow you to create truly rich domain models. There is also a LINQ to NHibernate project that allows you to use LINQ to query NHibernate in much the same way as you would use LINQ to SQL.
First let´s separate two different things:
Database modeling is concerned about the data while object modeling is concerned about entities and relationships.
Linq-to-SQL advantage is to quickly generate classes out of database schema so that they can be used as active record objects (see active record design pattern definition).
NHibernate advantage is to allow flexibility between your object modeling and database modeling. Database can be modeled to best reflect your data taking in consideration performance for instance. While your object modeling will best reflect the elements of the business rule using an approach such as Domain-Driven-Design. (see Kevin Pang comment)
With legacy databases with poor modeling and/or naming conventions then Linq-to-SQL will reflect this unwanted structures and names to your classes. However NHibernate can hide this mess with data mappers.
In greenfield projects where databases have good naming and low complexity, Linq-to-SQL can be good choice.
However you can use Fluent NHibernate with auto-mappings for this same purpose with mapping as convention. In this case you don´t worry about any data mappers with XML or C# and let NHibernate to generate the database schema from your entities based on a convention that you can customize.
On the other hand learning curve of Linq-to-SQL is smaller then NHibernate.
Or you could use the Castle ActiveRecords project. I've been using that for a short time to ramp up some new code for a legacy project. It uses NHibernate and works on the active record pattern (surprising given its name I know). I haven't tried, but I assume that once you've used it, if you feel the need to drop to NHibernate support directly, it wouldn't be too much to do so for part or all of your project.
As you written "for a person who have not used either of the them"
LINQ to SQL is easy to use so any one can use it easily
It also support procedures, which helps most of the time.
Suppose you want to get data from more than one table then write a procedure and drag that procedure to designer and it will create everything for you,
Suppose your procedure name is "CUSTOMER_ORDER_LINEITEM" which fetch record from all these three table then just write
MyDataContext db = new MyDataContext();
List<CUSTOMER_ORDER_LINEITEMResult> records = db.CUSTOMER_ORDER_LINEITEM(pram1, param2 ...).ToList<CUSTOMER_ORDER_LINEITEMResult>();
you can use you records object in foreach loop as well, which is not supported by NHibernate

Resources