CLR Triggers, Linq, And Transactions
Aug 14, 2007
I'm trying convert my working CLR Trigger to a Linq-based implementation, but I don't seem to be able to get Linq to cooperate with the Trigger's context transaction (a local SubordinateTransaction with IsolationLevel="ReadCommitted").
For brevity's sake I've boiled down my scenario to a bare minimum: A SQL table [Test] with three columns (int Manual, int Automatic, IDENTITY int ID) needs any external updates on its [Manual] column to be applied to its [Automatic] column (with an additional sign change) through a Trigger.
A fairly direct translation of my non-Linq CLR Trigger to Linq yields the following code (the [Trigger_TestLinQs] SQL table has been modified to point to the Trigger's "INSERTED" table, [TestLinQs] points to the actual SQL table):
Code Snippet[SqlTrigger(Name = "LinQTrigger", Target = "dbo.TestLinQ", Event = "FOR INSERT, UPDATE")]
public static void LinQTrigger()
{
SqlTriggerContext triggerContext = SqlContext.TriggerContext;
if (triggerContext.TriggerAction == TriggerAction.Insert || triggerContext.TriggerAction == TriggerAction.Update) {
//using (TransactionScope scope = new TransactionScope(Transaction.Current)) { /* err 6549 */ using (SqlConnection connection = new SqlConnection("context connection=true")) {
connection.Open();
using (MyDataContext context = new MyDataContext(connection)) {
List<int[]> updates = new List<int[]>();
foreach (Trigger_TestLinQ test in (from t in context.Trigger_TestLinQs select t)) { /* err 6522 */
if (test.Manual != null && triggerContext.IsUpdatedColumn(0))
updates.Add(new int[] { test.ID, -test.Manual.Value });
}
foreach (int[] update in updates) {
dbo.TestLinQ test = (from t in context.TestLinQs where t.ID == update[0] select t).Single<dbo.TestLinQ>();
test.Automatic = update[1];
}
context.SubmitChanges();
}
}
// scope.Complete(); //}
}
}
Running this on SQL Server 2005 / .NET 3.5 beta2 produces an Error 6522 "Cannot enlist in the transaction because a local transaction is in progress on the connection." in the line executing the Linq query because the Linq DataContext apparently insists on opening a transaction.
The recommended pattern for DataContext query operations - running them inside a TransactionScope as indicated by the commented-out sections - unfortunately leads to a different Error 6549 in the TransactionScope constructor complaining about a missing MSDTC. And there shouldn't be a need for a distributed transaction here, should there?
Using different TransactionScope constructors (TransactionScopeOptions.Required, TransactionOptions(){IsolationLevel=ReadCommitted}) did not make any difference, either.
What am I doing wrong here? Is there any way for the Linq DataContext to attach to the CLR Trigger's ambient transaction?
View 3 Replies
ADVERTISEMENT
Mar 21, 2007
I use the VB.NET transaction to update an sql server 2000 database. I call a number of stored procedures within this transaction.The stored procedures will update tables. These tables use triggers..My question is, when does the trigger get called? Is it after the each stored procedure, or is it after the whole transaction? Jag
View 6 Replies
View Related
Mar 2, 2014
A server I'm working on has a very unique situation, where user tables and production tables reside on the same database. Users update / create tables or populates these tables, so it can't be a table-specific trigger. However, they give a new meaning to "kamikaze pilots" as it's not uncommon for them to "accidentally" update / insert / delete 500,000,000 + records in a single statement. I've tried educating them to use batching, but to no avail, so now I'm forced to stop these statements BEFORE they execute, based on rowcount, as they fill up the database log so quickly that it goes into recovery mode (It has a 200GB log file - insane, I know).
I recon the mosts transactions allowed should be 1,000,000 records in a single statement. Looking for database trigger to stop them from executing statements with large records?
View 6 Replies
View Related
May 22, 2005
Hi there,
I have decided to move all my transaction handling from asp.net to stored procedures in a SQL Server 2000 database. I know the database is capable of rolling back the transactions just like myTransaction.Rollback() in asp.net. But what about exceptions? In asp.net, I am used to doing the following:
<code>Try 'execute commands myTransaction.Commit()Catch ex As Exception Response.Write(ex.Message) myTransaction.Rollback()End Try</code>Will the database inform me of any exceptions (and their messages)? Do I need to put anything explicit in my stored procedure other than rollback transaction?
Any help is greatly appreciated
View 3 Replies
View Related
May 12, 2008
This isn€™t an problem as such, it€™s more of a debate.
If a table needs a number of update triggers which do differing tasks, should these triggers be separated out or encapsulated into one all encompassing trigger. Speaking in terms of performance, it doesn€™t make much of an improvement doing either depending upon the tasks performed. I was wondering in terms of maintenance and best practice etc. My view is that if the triggers do totally differing tasks they should be a trigger each on their own.
www.handleysonline.com
View 12 Replies
View Related
Jan 8, 2008
Hello!
I try to get a list of ConditionsVersion where Version is MAX for each ConditionsVersion.
I tried something like this (as seen on http://msdn2.microsoft.com/en-us/vcsharp/aa336747.aspx#maxGrouped):
1 List<ConditionsVersion> list = (from cv in ConditionsVersions2 group cv by cv.FKConditions into cv3 select new { 4 PKConditions = cv.PKConditions,5 FKConditions = cv.FKConditions,6 MaxVersion = cv.GroupBy.Max(cv => cv.Version)7 CTimestamp = cv.Timestamp8 }).ToList();
But it doesn't work. It would be great if someone knows why.
Thank you!
View 2 Replies
View Related
Nov 2, 2007
Well, just played a little bit with that new thing from Microsoft. Genius! Microsoft presented that step backwards as a step forward.
Say good bye to the 3-tier architecture, now any programmer, after 1 week training, will be able to put SELECT * into the source code. No more stored procedures and logic on a server. No more ugly WHERE clauses. Just SELECT * and pass all records in a loop :)
When I looked at the queries, generated by LINQ in SQL profiler, I noticed that they are generated automatically using the same pattern. It is obvious, of course, but now it would be really difficult to trace a problematic query back to the C# code. All updates to table X will look like as identical twins!
On the other side, it is not so bad. We will have soon a lot of projects, failing when they go to the production and face the real volumes of data. And a long queue of companies, crying and asking to save them. Perfect “job security�. Please, use LINQ! Port all your code to LINQ immediately (Laughing demonically like Dr. Evil)
Hm… a second thought, but what could we suggest to these companies, having performance problems with LINQ 3rd party applications, when there is no source code? Now we could at least modify some stored procedures, and with LINQ looks like the only recommendation could be “contact a developer of that application or buy more a powerful server�.
View 18 Replies
View Related
Apr 20, 2008
Is it possible to use LINQ to SQL with Report Services? If so, are there any examples, tutorials, etc.?
View 1 Replies
View Related
May 28, 2008
Is Linq a feature of sql server 2008 ?
Or is it a feature of DOt net. Visual Studio 2008 ?
View 1 Replies
View Related
May 28, 2008
Some say linq to sql leads to the death of stored procedures is it correct ?
View 4 Replies
View Related
Nov 8, 2006
Will Linq be compatible with Sql Server Everywhere without having to add additional plugins?
View 7 Replies
View Related
Dec 30, 2007
Hullo am using Asp.Net 3.5, I want to create a usercontrol that is supported to all projects to upload file into sqlserver,
the user just give the database connection string,
tablename, column name depending upon their need, here I develop the
code using LINQ technology.
I Write a class with simple format like below,
using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.Linq;
/// <summary>
/// Summary description for FILE_MASTER_INSERT
/// </summary>
//namespace Linq2Sql_demo_doc
//{
[System.Data.Linq.Mapping.Table(Name = "FILE_MASTER")]
public partial class FILE_MASTER
{
string Tablename;
public FILE_MASTER()
{
//
// TODO: Add constructor logic here
//
}
[System.Data.Linq.Mapping.Column(Name="filename")]
public string FileName
{
get;
set;
}
[System.Data.Linq.Mapping.Column(Name = "file_content")]
public byte[] file_content
{
get;
set;
}
[System.Data.Linq.Mapping.Column(Name = "file_id", IsPrimaryKey = true, IsDbGenerated = true, CanBeNull = false)]
public int file_id
{
get;
set;
}
}
public class TestDB : DataContext
{
public Table<FILE_MASTER> FILE_MASTERs;
//Initializing base class constructor
public TestDB(string s) : base(s) { }
}
This
is working but, this is suitable only for single table, I expect
depending upon the user input automaticaly the tablename, column name
will change in the yellow block codes .
Is there any way to update the tablename , columnname from any other class?
Thank you. Jeyaseelan
View 1 Replies
View Related
Jan 21, 2008
I'm new to ASP/VS/Linq and I'm having a small problem.
I have one table setup in SQL Server Express 2005 through Visual Studio 2008. The table name is "Users" and has three columns (accountID, userName, email). AccountID is the primary key and set to auto incriment. I've added a couple of records by hand and it works.
I have a single form with a button, a label, and two text boxes. The button code is below. After entering some fake data that does not already exist in the database and clicking the button I get this.
Cannot insert explicit value for identity column in table 'Users' when IDENTITY_INSERT is set to OFF.
I understand that it is trying to insert something into the accountID field but I don't understand why since I'm only providing a username and e-mail address to insert.
Your help is greatly appreciated.protected void Button1_Click(object sender, EventArgs e)
{
MyDatabaseDataContext db = new MyDatabaseDataContext();
var query = from u in db.Users
where u.email == txtEmail.Text
select u;
var count = query.Count();
if (count == 0)
{
//Create a new user object.
User newUser = new User();
newUser.username = txtUsername.Text;
newUser.email = txtEmail.Text;
//Add the user to the User table.
db.Users.InsertOnSubmit(newUser);
db.SubmitChanges();
}
else
{
Label1.Text = txtEmail.Text + " already exists in the database.";
}
View 6 Replies
View Related
Jan 27, 2008
I have a supplier table with all my suppliers in it. I list them in a gridview. In this gridview, there is a link next to each record to an edit page. Below is the code for the edit page. Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim db As New orderLinqDataContext
Dim q = db.selectSupplierByID(Request.QueryString("id"))
Dim r As New System.Data.DataTable
txtFriend.Text = q(0).friendlyName
txtAdd1.Text = q(0).address1
txtAdd2.Text = q(0).address2
txtAdd3.Text = q(0).address3
txtAdd4.Text = q(0).address4
txtName.Text = q(0).supplierName
txtPhone.Text = q(0).phone
txtFax.Text = q(0).fax
txtPostCode.Text = q(0).postCode
End Sub
This causes a runtime error. The error is: "The query results cannot be enumerated more than once." and the txtAdd1.text line is highlighted.
How am I supposed to get at the data so I can fill my text boxes this way?
Thanks,
View 5 Replies
View Related
Mar 7, 2008
var query = from cloc in context.t_companylocs where (cloc.ref_company == companyid) && (cloc.street == attributes["Street"]) && (cloc.postalcode == attributes["Postalcode"]) && (cloc.country in countrylist) && (cloc.city in citylist) select cloc; attributes is a Dictionary<string, string> object.countrylist and citylist are List<string> objects.Of course the syntax above doesn't work. It's basically what I'm trying to achieve :-)A quick and dirty solution would be to just drop the two where constraints containing the "where in" statement and handle that part in the following foreach() loop.Can anyone please explain how you would do it properly?regards
View 1 Replies
View Related
Mar 12, 2008
Does anyone have a good example of how to insert data using System.Data.Linq? All the examples I've seen do something likeNorthwindDataContext db = new NorthwindDataContext();var x = new Product() {...}; db.Products.Add(x);db.SubmitChanges(); However I'm not seeing an Add method on System.Data.Linq.Table<T>. Has this changed? Could I somehow not be generating my model correctly?
View 2 Replies
View Related
Mar 20, 2008
Hello,
How can I get autogenerated value of inserted item with linq to sql?
Thanks
View 2 Replies
View Related
May 12, 2008
I would like to use LINQ to generate a sql statement that does not use LIKE, but rather uses CONTAINS. Is this possible? If not, my second question is whether or not I can parameterize a SqlCommand that uses CONTAINS. For example the following statement works just fine when I pass in the parameter via SqlCommand.Parameters.AddWithValue()SELECT * FROM [event] WHERE CONTAINS(comments, @searchTerm1)However, the following results in a variable not defined error.SELECT * FROM [event] WHERE (comments LIKE @searchTerm1)Any ideas? Thanks for your help.
View 1 Replies
View Related
May 25, 2008
Hi there,
In 2005.NET, if I used an asp:repeater, I would load the data from source and then manipulate it like so://load the data from source using a predefined connection and SQL Statement.private void LoadMyDataFromSource(){ try { connection.Open(); OleDbDataReader myReader = comm.ExecuteReader(); rptrCatList.DataSource = myReader; rptrCatList.DataBind(); myReader.Close(); } finally { connection.Close(); }} //catch the ItemDataBound event and manipulate the data how I wish before it's loaded into the Repeater.protected void rptrCatList_ItemDataBound(object sender, RepeaterItemEventArgs e) { if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) { int title = 4; //this is the index of the column I wish to manipulate((Label)e.Item.FindControl("lblTitle")).Text = ((IDataRecord)e.Item.DataItem).GetString(title) + ":" } }This would give me all the flexbility I ever needed. But now I wish to use linq and since the IDataRecord relies on dataReader sources, I cannot obtain the same flexbility. Can anyone point me in the right direction for obtaining the same kind of flexbility but using a linq-to-SQL dataContext? I wish to manipulate mostData that comes through from my source, so: //loadng the data in via my linq-to-sql context.private void LoadProducts() { MyDataContext db = new MyDataContext (); var all = from p in db.Products_IncontinenceStandards where p.Product_Cat == "Category1" select p; rpterCat.DataSource = all; rpterCat.DataBind(); }This is where I get stuck because, even though I can still capture the ItemDataBound event since I have databound the Repeater to the linqSource, I can't access the individual fields (or this is what I think I can't do!), Does anyone know how to relate to this so I can create the same effect? Many Thanks,Nathan Channon
View 4 Replies
View Related
Apr 24, 2008
Hi,
I am beginner in SQL Server So excuse me if my question is stange for you.
I have to work on an sql server 2005. I need to extract data from this server in XML file. I have look at a lots of thing and I find two solutions:
- Use SSIS
- Create a home made solution with LINQ in c#
Clearly I do not have enouth experience to see with solution are the most available? Which are the things required to use those solutions?
Thanks
View 12 Replies
View Related
Dec 2, 2007
Hi Guys,
I started working with linq and vb9.0 but i have a small problem i could feagure how to solve in c# but not in vb
I wanted to make left join or right join on vb 9.0 and linq is it possible or this is only c# feature ?
Waiting to hear from u guys,
Thanks
Softy
View 2 Replies
View Related
Dec 30, 2007
Hello, How do I add multiple data using LINQ, this one doesn't work. ... Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click Dim i As Integer For i = 0 To 3 Dim db As personalDataContext = New personalDataContext Dim p As personal = New personal p.name = "John" p.number = "01213" p.picture = "image/image.jpg" db.personals.InsertOnSubmit(p) Next End Sub... cheers,imperialx
View 1 Replies
View Related
Jan 7, 2008
I'm just starting to dabble around with LINQ and all of the examples I've come across all have 1 where clause. Is this intentional such that we are supposed to build queries on top of queries or is there a method in which I can add multiple predicates to my 1 query? I'm sorry if this sounds like a stupid question, I've been googling it to death and reading the few manuals on LINQ but like I said, all of the examples have had 1 where predicate.
Thanks,
Chance
View 2 Replies
View Related
May 3, 2008
hi, i'm working with LINQ to SQL and i have a table called Account, in that is Type, which is an int in the database but i map it to a AccountType enum, this works fine, but if i go into the dbml designer and change something later on, it gets errors, so i have to change all int->enum mappings back to int, recompile and then set them again! has anyone else had this? kindest regards
View 5 Replies
View Related
May 15, 2008
Here's my LINQ code:pl = (from p in db.Table where p.ID == 1 orderby p.NumericField descending select p).Take(7);
As you can see, I'm trying to sort by a numeric field. Specifically, it's a Numeric(5,0) field.
Problem is, the results aren't coming back numeric order. If this is good LINQ code, perhaps it's something else in my app. I just want to make sure this LINQ code is good.
Thanks in advance
View 1 Replies
View Related
Jun 2, 2008
Can I know the best method to connect the sql server 2008 with Visual studio 2008, it will be helpful if I know how to access the stored procedures in the sqlserver via LINQ.
View 1 Replies
View Related
Oct 1, 2013
I am trying to convert the following sql to linq
SELECT R.UserID,R.Cntrl_nbr FROM User R
WHERE (
R.REG_ID=
(SELECT MAX(B.REG_ID)
FROM User B
WHERE R.UserID = B.UserID )
The linq I am using is
var query = (from n2 in q1
where
n2.RegServiceTs == (q1.Where(c1 => c1.UserID == n2.UserID).Max(c2 => c2.REG_ID))
select n2).SingleOrDefault();
This is slow and is there a better way to do this?
View 1 Replies
View Related
Apr 17, 2008
We have an application that is built with WPF/.net 3.5 and leverages LINQ to SQL. Everything runs as expected when our application connects to MS SQL Server 2005. We have made a SQL CE version of our database using the Microsoft SYNC framework, and SQLMetal.exe to generate our .dbml.
The issue we are running into is that our application hangs while our LINQ to SQL objects are delay loading an EntitySet at random places throughout our code. After futher looking into the issue, and testing our published application on various workstations, we have discovered that the application does work on one computer that has SQL CE version 3.05.5365.0000. It does not however work on any computers that have SQL CE version 3.05.5386.0000.
We are logging the SQL queries that the LINQ to SQL is generating and when we execute them in the the Visual Studio 2008 Query Analyzer, they run successfully.
Any ideas are appreciated as we have hit a dead end.
Thanks!
View 5 Replies
View Related
Sep 1, 2007
I am getting a reference problem in APP_Code when I am creaing LinQ enabled website. When I am creating LinQ enabled website at that time it adds some dll like System.Query, System.Data.DLinq, System.Xml.XLinq and in web.config file it adds
<system.codedom> <compilers> <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CSharp.CSharp3CodeProvider, CSharp3CodeDomProvider"/> </compilers> </system.codedom>
automatically. Now the problem is when I add references like System.Query it does not show the Query namespace (It does not show any of the external dll added in the bin folder). And if we comment the
<system.codedom> <compilers> <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CSharp.CSharp3CodeProvider, CSharp3CodeDomProvider"/> </compilers> </system.codedom>
in web.config file it works properly that means it shows System.Query and other refrences.
Please if there is any solution do reply,
Thank You..
View 1 Replies
View Related
Dec 21, 2007
I have a GridView that is populated by a stored procedure via linq. I changed the stored procedure to return an additional column, but I can't get the additional column to show up in the GridView. The GridView has autogeneratecolumns=true, so if I were using a SqlDataSource the new column would show up automagically. But now it is not showing up and I cannot reference it. I can't figure out how to make linq recognize that my stored procedure has changed. I have tried deleting the sproc definition from the dbml file, making sure the partial class is removed the .vb file, refreshing the stored procedures list in database explorer, and adding the sproc definition back again (a hassle), but still it insists on defining only the original columns and not the new column. How do get linq to get back in sync with the database?
View 1 Replies
View Related
Feb 8, 2008
Hello,
I have my local development evrioment and my live webserver in colo. The two different machinces both have SQL2005 and copies of roughly the same database. I use the one for developement and the other obviously for production. Currently I read in different connection strings from my web.config file for my live version v my development version so I can have different database names and connection strings.
I'm looking at moving to LINQ, but I can't figure out how I'd achive an equivelent flexibility as database names and connection strings seem to be hardcoded in to the class using it's designer. Obviously if modifing this wasn't possible, nobody would be using LINQ, so how do I work around this?
Thanks,
Joel Barsotti
View 1 Replies
View Related
Feb 29, 2008
I need some help. I have a function that used to use ADO.NET to return a dataview. Now I'm using linq, and I don't know how to make this work anymore.my original function looked like this: public DataView getIssue() { //do some ADO, return the dataview return ds.Tables["Articles"].DefaultView; } With this I could write Gridview1.dataSource = getIssue();I want to do the same thing with Linq, but I'm running into some trouble:Here's my function now:public DataView getIssue() { var query = from a in db.Articles join i in db.Issues on a.IssueID equals i.IssueID select a; DataView dv = new DataView(); dv = query.asdatatable(); return query; }OK, first off I can't use asdatatable since I am using a join, so I can't make the results of my query a dataview. I can't return the results of my query in this function, something that seemed simple to do in Linq now seems like something that may only be possible in ADO.Thanks for your time
View 5 Replies
View Related
Mar 25, 2008
Hi to all , I wrote a stiored procedure like below SET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGOALTER PROCEDURE SELET_AND_RETURN ( @opId Nvarchar(50) output)ASBEGIN SET NOCOUNT ON; SELECT @opId = NAME FROM TABLE1 PRINT @opId RETURN @opId;ENDGONow i include this procedure into my project, my problem is i dont know how to pass the output parameter from front end coding,
View 2 Replies
View Related