Since I switch languages constantly, I'm always trying to remember the right syntax; so, this is my place to have it, for now. Before you can connect to your DB, you need to run a VS tool, that will generate the LINQ for your particular schema (and you need to rerun every time you change :( . In my case, the generated code is in the SimpleBlog package, and the generated class is SimpleBlogDataContext; so my code for reading something looks like:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
SimpleBlog.SimpleBlogDataContext ctx = new SimpleBlog.SimpleBlogDataContext(); | |
var blogs = from b in ctx.Blogs | |
select b; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
protected void AddBlog_Click(object sender, EventArgs e) | |
{ | |
SimpleBlogDataContext ctx = new SimpleBlogDataContext(); | |
Blog b = new Blog(); | |
b.Title = BlogTitle.Text; | |
ctx.Blogs.InsertOnSubmit(b); | |
try | |
{ | |
ctx.SubmitChanges(); | |
} | |
catch (Exception e1) | |
{ | |
Console.WriteLine(e1); | |
} | |
} |
Notice that the context (ctx here) needs to be a global variable; having several contexts will diminish performance and probably confuse you, since variables from one context cannot be saved in another.
We always need to import the System.Linq namespace when using linq; If we're doing this directly in an aspx page we use an import directive, like:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<%@ Import namespace="System.Linq" %> |
No comments:
Post a Comment