开发者

Dynamically built LINQ to SQL query without Entity classes

LINQ2SQL is pretty good. Easy to build entity classes and use it.

but what if I don't know at compile time nothing about the database, and tables?

but I need t开发者_高级运维o query "Foo" table in "FooDb";

Can I run Linq queries against a DB without any Entity classes?

Could you show me an example?


Linq2Sql is an ORM - an Object Relational Mapper.

As such, it needs to know the database structure in order to generate classes that you can interact with, before your application is compiled.

In short, what you are asking is not possible with Linq2Sql or any other ORM I know of.


You can create an application that will query the system tables and generate and load classes for you, but I wouldn't know how you would interact with them in code without knowing the structures in advance.


There must be compiled entities somewhere in order for LINQ to SQL to work. Therefore, the only way to have a dynamic model is to build a dynamic assembly, the way LINQPad does. It's possible, but it's a lot of work. Besides, what would your LINQ query look like if you don't know what the database looks like?


No, you cannot build your object model dynamically, or on-the-fly.

The only related (and non-optimal, counter-intuitive, and hard-to-maintan) way to do what you want would be to:

  • create an ad-hoc SQL statement. SELECT ID FROM Foo;
  • execute that statement using DataContext.ExecuteCommand()


Ok. What about WebMatrix.Data?

If you need easy access to database and don't wanna be bothered with opening connection, closing, and such stuff. And your project doesn't need strongly-typed entities.

Here's something that Jeffrey Palermo at MVCConf showed. The piece of code like this:

using WebMatrix.Data;

...

public IEnumerable<dynamic> Execute(){

   Database db = Database.Open("EasyTimeTracking");
   var employees= db.Query("select FullName, Startdate, EndDate from Employee");
   return employees;

}

Is it worth enough to use instead of old way of doing SQL stuff in c#? What do you think?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜