How to write sql to get data when using postgresql and EF? - database

I have the below C# and Entity framework 6.4 code to get data from
postgresql function
return Database.SqlQuery<TEntity>(sql, parameters).ToArrayAsync();
and I tried
var sql = $#"select * from GetLogs(?,?,?,?,?,?,?,?,?,?,?,?,?)"; or
var sql = $#"select * from GetLogs($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13)";
but got failed, anybody know about it?
I also try
var sql = "select * from GetLogs(TO_TIMESTAMP({0},'YYYY-MM-DD HH24:MI:SS'), TO_TIMESTAMP({1},'YYYY-MM-DD HH24:MI:SS'),{2},'{3}','{4}',{5},'{6}','{7}',{8},{9},{10})";
var from = request.From.ToString("yyyy-MM-dd HH:mm:ss");
var to = request.To.ToString("yyyy-MM-dd HH:mm:ss");
return Database.SqlQuery<AdminLogMasterModel>(sql,
from,
to,
request.HttpStatusCode,
request.ServerName,
request.Page,
request.TrackingId,
request.Content,
request.SortBy,
request.OrderBy == SortOrder.Ascending ? 0 : 1,
request.Page,
request.Rows).ToArrayAsync();
This got no error but no date return. It seems postgresql didn't pass parameter in EF.

I tried the below code can work
var sql = "select * from GetLogs(TO_TIMESTAMP(#p0,'YYYY-MM-DD HH24:MI:SS'),TO_TIMESTAMP(#p1,'YYYY-MM-DD HH24:MI:SS'),#p2,#p3,#p4,#p5,#p6,#p7,#p8,#p9,#p10)";
var para = new NpgsqlParameter[]
{
new NpgsqlParameter("#p0", request.From.ToString("yyyy-MM-dd HH:mm:ss")),
new NpgsqlParameter("#p1", request.To.ToString("yyyy-MM-dd HH:mm:ss")),
new NpgsqlParameter("#p2", CreateRequestValueifNull(request.HttpStatusCode)),
new NpgsqlParameter("#p3", CreateRequestValueifNull(request.ServerName)),
new NpgsqlParameter("#p4", CreateRequestValueifNull(request.Path)),
new NpgsqlParameter("#p5", CreateRequestValueifNull(request.TrackingId)),
new NpgsqlParameter("#p6", CreateRequestValueifNull(request.Content)),
new NpgsqlParameter("#p7", request.SortBy),
new NpgsqlParameter("#p8", request.OrderBy == SortOrder.Ascending ? 0 : 1),
new NpgsqlParameter("#p9", request.Page),
new NpgsqlParameter("#p10", request.Rows),
};
return Database.SqlQuery<LogModel>(sql, para).ToArrayAsync();

Related

How to execute huge SQL queries rapidly with EFCore?

Here are two simplified examples of SQL queries I recently run on my SQL database:
insert into new_entity
select top 10000 field1,
field2
from old_entity
&
update top 1000 e
set field1 = 13
from entity e
where field1 is null
Their execution was so fast it's barely noticeable.
However, if I want to perform the same operation using EF, the way I know would be iterating over each object:
using(var db = new myDbContext())
{
var new_objs = db.old_entity.Take(10000).Select(ot=> new new_entity() { ... });
db.new_entity.AddRange(new_objs);
db.SaveChanges();
}
&
using(var db = new myDbContext())
{
var objs = db.entity.Where(e => e.field1 == null).Take(1000);
objs.ForEach(e => e.field1 = 13);
db.SaveChanges();
}
Which lasted for hours, which is unacceptable.
I can execute a raw SQL query from within the app, but for real-life complex objects, it's a dradgery.
Is there a way to code such operations using the EF model with a performance of a directly written query?
EF Core 7 have introduced new method ExecuteUpdate. And your query for update can be written in the following way:
using(var db = new myDbContext())
{
var objs = db.entity.Where(e => e.field1 == null).Take(1000);
objs.ExecuteUpdate(b => b.SetProperty(x => x.field1, x => 13));
}
INSERT FROM is not supported by EF Core any versions.
Anyway, you can install third-party extension linq2db.EntityFrameworkCore, note that i'm one of the creators.
Insert
using(var db = new myDbContext())
{
var new_objs = db.old_entity.Take(10000).Select(ot=> new new_entity() { ... });
new_objs.Insert(db.new_entity.ToLinqToDBTable());
}
Update
using(var db = new myDbContext())
{
var objs = db.entity.Where(e => e.field1 == null).Take(1000);
objs
.Set(x => x.field1, x => 13)
.Update();
}

Using Integrated security for DB connection in Google Docs Script?

I want to establish a connection to MS SQL in Google docs via Script by using integrated security = SSIP, basically connecting to the server with my integrated Windows authentication. However, Google tells me that the 'integrated security' connection property is unsupported. I tried phrasing it differently (trusted_security etc.) but nothing works.
Does anyone know a workaround?
I used the query google offered below.
// Replace the variables in this block with real values.
var address = 'database_IP_address';
var user = 'user_name';
var userPwd = 'user_password';
var db = 'database_name';
var dbUrl = 'jdbc:mysql://' + address + '/' + db' integrated security = ssip;
// Read up to 1000 rows of data from the table and log them.
function readFromTable() {
var conn = Jdbc.getConnection(dbUrl, user, userPwd);
var start = new Date();
var stmt = conn.createStatement();
stmt.setMaxRows(1000);
var results = stmt.executeQuery('SELECT * FROM entries');
var numCols = results.getMetaData().getColumnCount();
while (results.next()) {
var rowString = '';
for (var col = 0; col < numCols; col++) {
rowString += results.getString(col + 1) + '\t';
}
Logger.log(rowString)
}
results.close();
stmt.close();
var end = new Date();
Logger.log('Time elapsed: %sms', end - start);
}

SQL Server DAC FX SchemaComparison SchemaCompareDatabaseEndpoint fails with no IntegratedSecuirty

I am trying to find newly created tables in the target database on publishing. Using DAC Fx I am able to find the differences and delete the tables after moving the newly created table to another db.
I developed and tested the code with IntegratedSecurity. Started failing on machines with SQLServer logins.
The moment I toggle the IntegratedSecurity to true it works. Is it a bug?
private void Analyse()
{
try
{
var sourceDacpac = new SchemaCompareDacpacEndpoint(DacPacSrc);
var csb = new SqlConnectionStringBuilder(ConnectionString);
csb.IntegratedSecurity = false;
var targetDatabase =new SchemaCompareDatabaseEndpoint(csb.ToString());
var comparison = new SchemaComparison(sourceDacpac, targetDatabase);
comparison.Options.DropObjectsNotInSource = true;
var result = comparison.Compare();
if (result.GetErrors().Any())
{
throw new Exception("Compare failed " + result.GetErrors().FirstOrDefault().Message);
}
var delta = new List<string>();
if (result.Differences != null && result.Differences.Any())
{
var deltaTables = result.Differences.Where(x => x.Name == "Table" && x.UpdateAction == SchemaUpdateAction.Delete);
delta = deltaTables.Select(x => x.TargetObject.Name.ToString()).ToList();
}
FindingDeltaCompleted?.Invoke(this, new DeltaEventArgs(delta));
}
catch (Exception ex)
{
Logging.HandleException(ex);
}
}
Try setting Persist Security Info=True in the SQL Authentication connection string.
SSDT/DAC Fx saves connection strings in registry under HKEY_CURRENT_USER\SOFTWARE\Microsoft\SSDT\ConnectionStrings. When Persist Security Info=True is not set, it won't restore the password when loading the connection strings from registry.

local database null result

I am trying to create a local database. I made some inserts, but when I run the code I get the "result = null" error:
var selectStmt:SQLStatement = new SQLStatement();
selectStmt.addEventListener(SQLErrorEvent.ERROR, dbErrorHandler);
selectStmt.sqlConnection = conn;
selectStmt.text = "SELECT * FROM table1";
selectStmt.execute();
var result:SQLResult = selectStmt.getResult();
var numResults:int = result.data.length;
How can I fix this?
SQLStatement is asynchronous, you could do "getResult()" only in a "flash.events.SQLEvent.RESULT" event listener

problem with update strong typed dataset turn to database in C# .net framework 3.5

I want to remove some special characters in a table of database. I've used strong typed table to do it. When i got all data into dataset from database and modified it then i called method update() of data adapter to turn dataset to database but it doesn't work.
Below is my code
DsTel tel = new DsTel();
DsTelTableAdapters.telephone_bkTableAdapter adapter = new DsTelTableAdapters.telephone_bkTableAdapter();
adapter.Connection = new SqlConnection(ConfigurationManager.AppSettings["SiteSqlServer"].ToString());
adapter.Fill(tel.telephone_bk);
foreach (DsTel.telephone_bkRow row in tel.telephone_bk.Rows)
{
row.telephoneNo = RemoveWhiteSpace(row.telephoneNo.ToString());
row.AcceptChanges();
}
tel.AcceptChanges();
adapter.Update(tel.telephone_bk);
Please give me some ideas?
Thanks in advance.
I've found the solution for this problem by using the TableAdapterManager.
Below is my code:
DsTel tel = new DsTel();
DsTelTableAdapters.telephone_bkTableAdapter adapter = new DsTelTableAdapters.telephone_bkTableAdapter();
adapter.Connection = new SqlConnection(ConfigurationManager.AppSettings["SiteSqlServer"].ToString());
adapter.Fill(tel.telephone_bk);
foreach (DsTel.telephone_bkRow row in tel.telephone_bk.Rows)
{
if (!row.IstelephoneNoNull())
{
row.telephoneNo = RemoveWhiteSpace(row.telephoneNo.ToString());
}
}
DsTelTableAdapters.TableAdapterManager mrg = new DsTelTableAdapters.TableAdapterManager();
mrg.telephone_bkTableAdapter = adapter;
mrg.BackupDataSetBeforeUpdate = true;
mrg.UpdateAll((DsTel)tel.GetChanges());
You've called AcceptChanges before the update. This means the dataset has no changes any more so there is nothing to send to the database.
Remove all of the calls to AcceptChanges and add one AFTER the update. ie:
DsTel tel = new DsTel();
DsTelTableAdapters.telephone_bkTableAdapter adapter = new DsTelTableAdapters.telephone_bkTableAdapter();
adapter.Connection = new SqlConnection(ConfigurationManager.AppSettings["SiteSqlServer"].ToString());
adapter.Fill(tel.telephone_bk);
foreach (DsTel.telephone_bkRow row in tel.telephone_bk.Rows)
{
row.telephoneNo = RemoveWhiteSpace(row.telephoneNo.ToString());
}
adapter.Update(tel.telephone_bk);
tel.telephone_bk.AcceptChanges();

Resources