简体   繁体   中英

Linq to Sql - Create DB and How to query from it?

I create a table using Linq

PODataContext db = new PODataContext();

String query = "create table myTable(text varchar(20) primary key)";

db.ExecuteCommand(query);

Then I also inserted data to it.

String insQuery = "insert into myTable values('some text')";

db.ExecuteCommand(insQuery);

My problem is how do I get data from that table ?

Thank You yohan

var query =from  c in new PODataContext().myTable
            select c;

UPDATED

LINQ to SQL without using the Object Relational Designer

Create a class named MyTable and decorate with Table attribute.

[Table(Name="myTable")]
public class MyTable

{
    [Column]
    public string Text 

}

Then create following class

public class PODataContext : DataContext
  {

   public Table<MyTable> myTables;

    public PODataContext(string connection): base(connection)

    {

    }

}

Now query your table as follows

var query =from  c in new PODataContext().myTable
            select c;

To do a query to the database table you don't need to write string commands and call the ExecuteQuery method - it is only for specific database tasks that you can't do with LINQ. What you can do with LINQ is write queries like:

var query = from c in db.myTable
            where c.Id > 5
            select c;

foreach ( var c in query )
    Console.WriteLine( c );

This code take all entities from myTable that have the Id greater than 5 ( SELECT * FROM myTable WHERE Id > 5 in SQL ) and write them all to the console.

But to make it work you need to create right DataContext for your database. The simpliest way to do it in Visual Studio is to Add New Item... -> LINQ to SQL Classes . Then you need to connect to your database in Server Explorer , expand Tables and drag needed tables to designer window. Visual Studio automatically generates new class derived from DataContext that usefull for you database (for example has properties like myTable ).

MSDN page for LINQ to SQL

If you are going to change (or create!) the database schema at runtime, note that LinqToSQL cannot update it's database representation at runtime as well. It can only be updated by Drag-And-Drop in Visual Studio or using SQLMetal via command line (a rather obscure method) and recompiling your application.

However, you could create a well-defined database schema with the ExecuteQuery at runtime and use the same existing database schema on your development machine to generate your LinqToSQL DataContext via drag and drop as usual.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM