How to pass criteria to a SQL Server query? - c#

Used by:
EntityFramework - 6.2.0;
MS Sql Server 2012;
In MS Access, I use the following query(req_GroupsStud_CurGroup):
SELECT req_GroupsStud_Stud.*, req_GroupsStud_Stud.id_group
FROM req_GroupsStud_Stud
WHERE (((req_GroupsStud_Stud.id_group)=[Forms]![frm_00_00_MainForm]![id_group_Frm]));
 
From the form, using the expression [Forms]![Frm_00_00_MainForm]![Id_group_Frm], the parameter [id_group_Frm] is passed to the request.
Questions.
How in MS Sql Server to transfer in the query req_GroupsStud_CurGroup parameter
`id_group_Frm "?
Or are there other tools in MS Sql Server and EntityFramework to get a similar data set?
Update_1:
Requirements for the request req_GroupsStud_CurGroup:
1. if changes are made to the record in the request, these changes should be displayed in the original source;
if the record is added to the request, then this record is displayed in the source;
the request is planned to be used in another request.
I managed to implement these requirements in MSAccess.
I do not understand how to do the same using Entity-Framework and MS SQL Server.
I tried the following methods:
- method_1
cntDB.req_GroupsStud_Stud.Load();
System.Data.SqlClient.SqlParameter id_group_Param = new System.Data.SqlClient.SqlParameter("#id_group_frm", id_group);
var sp_Get_Stud_var = cntDB.Database.SqlQuery<req_GroupsStud_Stud>("sp_Get_Stud #id_group_frm", id_group_Param).ToList();
bs_Grid_2.DataSource = sp_Get_Stud_var;
dataGridView2.DataSource = bs_Grid_2;
- method_2
cntDB.sp_Get_Stud(id_group);
Can not fully understand.
I think these methods will not meet the above requirements for the request.

Related

DirectConnection cannot be used when ConnectionModeSwitch is set to UseConnectionMode while connect with Azure Cosmos DB API for MongoDB

I want to connect with Azure Cosmos DB API for MongoDB via ASP.NET app. To start I use connection string provided by Microsoft (when creating an instance by Azure)
var client = new MongoClient("mongodb://[myInstanceName]:
[primaryAccountKey]#[myInstanceName].documents.azure.com:10255/?ssl=true&retrywrites=false&replicaSet=globaldb
&maxIdleTimeMS=120000&appName=#mongocosmocoffedb#");
var database = client.GetDatabase("productdb");
var collection = database.GetCollection<Product>("productcollection");
return Ok(collection);
But when I use this connection string I got error
DirectConnection cannot be used when ConnectionModeSwitch is set to UseConnectionMode.
I found this stackoverflow topic and try use
var client = new MongoClient("mongodb://[myInstanceName]:
[primaryAccountKey]#[myInstanceName].documents.azure.com:10255/?ssl=true");
but in this case i got error
MaxWireVersion is not known.
This is the connection mode port issue. The port number you mentioned 10255 is used for geo-replication and that is causing the issue. Post numbers 10255, 10256 map to the instance that has geo-replication.
Change the port number to 10255. 10250 maps to the default Azure cosmos DB API for Mongo DB. In case of using geo-replication, public end point you can use 10255
Refer the following link: https://learn.microsoft.com/en-us/azure/cosmos-db/sql/sql-sdk-connection-modes

How to make SqlConnection.RetrieveStatistics work?

I can't make SqlConnection.RetrieveStatistics work, it always return a hashtable of 18 elements that are all zeros.
What I want to do : In my test environnent, I want to add a header for each httpresponse with the number of sql commands that were executed during the request processing.
My app is only (Rest) webservices, I have one sql connection par request ( One NHibernate session per request ).
After the request is processed, I do :
var connection = statelessSession.NHSession.Connection as ReliableSqlDbConnection;
if (connection != null)
queries += Convert.ToInt32(connection.ReliableConnection.Current.RetrieveStatistics()["Prepares"]);
The number is always 0, and when I break on this line, I see that all numbers are zeros.
After the session is opened, I do :
var ret = module.OpenSession();
var connection = (ret.Connection as ReliableSqlDbConnection);
if(connection != null)
{
connection.ReliableConnection.Current.StatisticsEnabled =true;
ret.CreateSQLQuery("SET STATISTICS IO ON; SET STATISTICS TIME ON;").ExecuteUpdate();
connection.ReliableConnection.Current.ResetStatistics();
}
return ret;
I use https://github.com/MRCollective/NHibernate.SqlAzure because in production I'm using sql azure, but in local I have an instance of Sql Server 2014 Developer Edition.
For my database, I have :
Auto create statistics true
Auto update statistics true
Did I miss something ?
The cause of this was that NHibernate opens a new connection for each request, this is why I was loosing the statistics each time.

Getting CREATE TABLE permission denied in database in EF6.1 while executing stored procedure

I am trying to fetch some records from a stored procedure in EF 6 using code first approach. Initially it was working as I was using 'sa' login for connection string. When I changed the login details in connection string it started throwing error
CREATE TABLE permission denied in database
For information I have disabled right on the database for accessing table. And so I am using stored procedures to access the data for all user excepts for sa user. I went into SQL Server profiler to see what actually the query is doing and saw its trying to create a table of my entity.
This is my code:
public IEnumerable<_BankHoliday_SP> _BankHoliday_SP
{
get
{
var content = _dbContext.Database.SqlQuery<_BankHoliday_SP>("exec spConfigBankHolidayGet");
return content;
}
}
And when I try to access the data from the ViewModel class.
var bankHolidayList = _repository._BankHoliday_SP.ToList();
I am getting the error.
try executing sp from sql server
EXEC proc_name
if it works no need to pass exec with sp name
var content = _dbContext.Database.SqlQuery<_BankHoliday_SP>("exec spConfigBankHolidayGet");
to
var content = _dbContext.Database.SqlQuery<_BankHoliday_SP>("spConfigBankHolidayGet");

DocumentDb query with both ordering and paging on the server side, possible?

I am writing an API to allow a client to consume time-ordered data. There is a lot of it (10k+ records per client) so I don't want to dump all of it this back to the client and order there, hence my need to both order it and page it server-side. I have the paging working, but I cannot see how to add ordering.
I've seen recommendations to sort on the client, but given the potential amount of data that is not going to work in this case. Is there a workaround?
Here is what I have so far:
var options = new FeedOptions {
MaxItemCount = 25,
RequestContinuation = continuationToken
}
var query = String.Format("SELECT * FROM TimelineEvent t WHERE t.acc_id = '{0}' AND t.removed != true", accountId);
// ORDER BY in the query text doesn't appear to work
var events = client.CreateDocumentQuery<TimelineEvent>(colSelfLink, query, options).AsDocumentQuery();
var response = await query.ExecuteNextAsync<TimelineEvent>();
It's not supported out of the box, but you can implement a stored procedure that does this.
The msft product group has supplied some code samples here: https://code.msdn.microsoft.com/windowsazure/Azure-DocumentDB-NET-Code-6b3da8af/sourcecode?fileId=132409&pathId=34503205
Look under server side script, JS folder, you'll see an "orderby" script that does this. Adjust to your needs and try it.
ORDER BY is now officially supported by DocumentDB
https://azure.microsoft.com/en-us/documentation/articles/documentdb-orderby/

Serialize linq query so that it can be executed somewhere else

I am creating a client application that connects to a website in order to execute queries. I am not enabling the client to connect directly to the database but he can perform queries through the website.
The way I execute queries through the website is through linq. For example I may do:
MyEntities db = new MyEntities();
var customers = db.Customers.ToList();
Since the client does not have the connection string and sql server does not allow remote connections when he executes the above code it will obviously not work. My question is how can the client send that query to the web service?
The reason why I need this is because there are so many different types of queries and for each different one I have to create a different page. For example I have GetInvoices.aspx, GetCustomers.aspx, and I am always creating new ones just because I dont want the client to connect directly to the database. It will be nice if I could serialize the linq query and send that to the server. the server then should validate that I am not doing a delete statement for example and if thats the case then execute the query.
Eidt
This is what I am going to do for only select statements:
// Note connection string only have basics. It does not have password nor database.
public static string GenerateSelectQuery<T>(Func<Common.Data.TcEntities, IQueryable> method)
{
Common.Data.TcEntities db = new Common.Data.TcEntities(#"metadata=res://*/Data.Model1.csdl|res://*/Data.Model1.ssdl|res://*/Data.Model1.msl;provider=System.Data.SqlClient;provider connection string=""""");
var query = method(db);
return query.ToString();
}
then if I wish to create a custom query I will do:
var query = GenerateSelectQuery<Customer>(db => db.Customers.Where(x=>x.FirstName.Contains("a")));
I will send then that string to the server and expect an array of Customers. On the server side I will make sure string starts with select and it does not contain --.
Implementing a WCF Data Services, http client can query your data using the OData protocol.
For example, applying a select Name on your customers collections will be queryable using the http url:
http://youdomain/yourWCFDataServices.svc/Customers()?$select=Name

Categories

Resources